views:

180

answers:

2

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?

+12  A: 

But the problem now is that I can't make "head" and "tail" ranges using begin() and end() because those aren't reverse iterators.

reverse_iterator::base() is what you are looking for - section new members on SGIs reverse_iterator description or here on cplusplus.com

Georg Fritzsche
Excellent. Thank you!
Adrian McCarthy
Note that `reverse_iterator::base()` doesn't point to the same element, but instead to the element after the found item. Scott Meyer's expressed it best in guideline 3 in this article: http://www.ddj.com/cpp/184401406
AFoglia
+3  A: 

What about std::find_end? (To find the last occurrence of a sequence)

Jesse Emond
+1 for interesting approach. Looking for the last subsequence of one element certainly would work. But converting the reverse iterator to it's base type is more efficient.
Adrian McCarthy