Get index in vector from reverse iterator

I know how to get an index from a vector iterator by subtracting the beginning iterator from it. For example:

vector<int>::iterator it = find(vec.begin(), vec.end(), x); size_t position = it - vec.begin(); 

However, now I want to find the index of the last x in the vector. How can I get the real index from reverse iterators? I found the following that seems to work (editing: this is not), but maybe there is a better (more idiomatic or any other) way.

 vector<int>::reverse_iterator it = find(vec.rbegin(), vec.rend(), x); size_t position = vec.size() - (it - vec.rbegin()); 
+7
c ++ iterator reverse-iterator find vector
source share
2 answers

I would use:

 #include <algorithm> #include <iostream> #include <vector> int main() { auto v = std::vector<int> { 1, 2, 3 }; auto rit = std::find(v.rbegin(), v.rend(), 3); if (rit != v.rend()) { auto idx = std::distance(begin(v), rit.base()) - 1; std::cout << idx; } else std::cout << "not found!"; } 

Live example .

The reason for -1 calculating the distance is due to the conversion between the reverse and regular iterators in the .base() member:

24.5.1 Reverse iterators [reverse.iterators]

1 An example of an inverse-iterator pattern is an iterator adapter that iterates from the end of the sequence defined by its base iterator to the beginning of this sequence. The fundamental relationship between the inverse of the iterator and its corresponding iterator is I set identity: &*(reverse_iterator(i)) == &*(i - 1) .

Note You can also use the above code without checking on v.rend() and use a convention that idx == -1 equivalent to an element that was not found. However, this loses the ability to do v[idx] , so you will eventually need to check for this.

+5
source share

You can use:

container.size() - 1 - (iterator - container.rbegin())

or

container.size() - 1 - std::distance(container.rbegin(), iterator)

Additional information on reverse iterators. How to use reverse iterators without confusion . To convert inverse iterators to forward iterators and more.

0
source share

All Articles