获取插入向量的对象的索引 [英] Get index of object inserted into a vector
本文介绍了获取插入向量的对象的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获得对象实际插入的位置?
How can I get the position where my object was actually inserted?
#include <vector>
using namespace std;
vector<SomeClass> list;
SomeClass object;
list.push_back(object);
list[...].method(); // I do not have the key
不幸的是 push_back
没有返回任何东西,因为它的返回类型是 void
.
Unfortunately push_back
does not return anything since its return type is void
.
推荐答案
如果 v
是你的向量,下面会给你位置(即索引):
If v
is your vector, the following will give you the position (that is, the index):
v.push_back(object);
size_t pos = v.size() - 1;
或者你可以在调用push_back()
之前查看size()
.那么你就不需要减一了.
Or you can look at the size()
before calling push_back()
. Then you won't need to subtract one.
这篇关于获取插入向量的对象的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文