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());
c ++ iterator reverse-iterator find vector
Neil kirk
source share