Using STL, I want to find the last instance of a certain value in a sequence.
This example will find the first instance of 0 in a vector of ints.
#include <algorithm>
#include <iterator>
#include <vector>
typedef std::vector<int> intvec;
intvec values;
// ... ints are added to values
intvec::const_iterator split = std::find(values.begin(), values.end(), 0);
Now I can use split
to do things to the subranges begin()
.. split
and split
.. end()
. I want to do something similar, but with split set to the last instance of 0. My first instinct was to use reverse iterators.
intvec::const_iterator split = std::find(values.rbegin(), values.rend(), 0);
This doesn't work because split is the wrong type of iterator. So ...
intvec::const_reverse_iterator split = std::find(values.rbegin(), values.rend(), 0);
But the problem now is that I can't make "head" and "tail" ranges using begin()
and end()
because those aren't reverse iterators. Is there a way to convert the reverse iterator to the corresponding forward (or random access) iterator? Is there a better way to find the last instance of an element in the sequence so that I'm left with a compatible iterator?