问题
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
Unfortunately push_back
does not return anything since its return type is void
.
回答1:
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;
Or you can look at the size()
before calling push_back()
. Then you won't need to subtract one.
回答2:
You can use the back() member to obtain a reference to the last element:
list.push_back(object);
list.back();
Or, since push_back() simply adds the object to the end, the index of the newly-inserted element is the vector size minus one:
list.push_back(object);
vector<my_class>::size_type object_pos = list.size() - 1;
回答3:
If you need to locate a particular element after you have them, and you don't want to save the index ahead of time (in case you do something to the vector like sort/add/remove/etc), you could also use the find algorithm.
回答4:
While NPE's correct answer shows a pragmatic POV, I concentrate on the reasoning for this simple answer. The observable behaviour is just the purpose of the push_back member function:
Appends the given element value to the end of the container.
So the index is always equal to v.size()
before insertion or, equivalently, v.size()-1
after insertion. If this assertion cannot been fulfilled, the capacity of the container could not be grown or your class throws an exception in the copy/move constructor (see section Exceptions in the documentation).
来源:https://stackoverflow.com/questions/13879484/get-index-of-object-inserted-into-a-vector