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
.
The simplest solution is to use the std::find algorithm defined in the <algorithm> header. The idea is to get the index using std::distance on the iterator returned by std::find , which points to the found value. We can also apply pointer arithmetic to the iterators. Therefore, the - operator would also work.
Indexing works on Vectors, So just Acces it by using index. Similar to arrays.
std::vector::insert() is a built-in function in C++ STL that inserts new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.
For min index we will use std distance with v begin function and the iterator will start checking the first value. and for max index we will start checking with the second element. So the iterators will check the whole vector for max and min element and their return its index. Output will be in (min_idex, max_index).
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With