Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of object inserted into a vector

Tags:

c++

std

stl

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

Unfortunately push_back does not return anything since its return type is void.

like image 719
danijar Avatar asked Dec 14 '12 13:12

danijar


People also ask

How do you find the index of an object in a vector?

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.

Can you index into a vector?

Indexing works on Vectors, So just Acces it by using index. Similar to arrays.

How do you add an element to a specific index in vector?

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.

How do you find the index of a minimum element in a vector?

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).


2 Answers

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.

like image 63
NPE Avatar answered Oct 23 '22 02:10

NPE


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;
like image 26
Daniel Trebbien Avatar answered Oct 23 '22 03:10

Daniel Trebbien