Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator to last element of std::vector using end()--

I have a std::vector and I want the iterator to the last element in the vector; I will be storing this iterator for later use.

NOTE: I want an iterator reference to it, not std::vector::back. Because I want to be able to compute the index of this object from the std::vector::begin later on.

The following is my logic to get the iterator to the last element:

std::vector<int> container;
std::vector<int>::iterator it = container.end()--;

Since std::vector::end has O(1) time complexity, is there a better way to do this?

like image 315
Quark Avatar asked May 04 '16 02:05

Quark


2 Answers

I think you mean either:

std::vector<int>::iterator it = --container.end();
std::vector<int>::iterator it = container.end() - 1;
std::vector<int>::iterator it = std::prev(container.end());

You're unintentionally just returning end(). But the problem with all of these is what happens when the vector is empty, otherwise they're all do the right thing in constant time. Though if the vector is empty, there's no last element anyway.

Also be careful when storing iterators - they can get invalidated.

Note that if vector<T>::iterator is just T* (which would be valid), the first form above is ill-formed. The second two work regardless, so are preferable.

like image 63
Barry Avatar answered Oct 09 '22 19:10

Barry


You have rbegin that does what you need

cplusplus reference

auto last = container.rbegin();
like image 35
dau_sama Avatar answered Oct 09 '22 20:10

dau_sama