Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an STL algorithm to find the last instance of a value in a sequence?

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 like begin(), split and split, 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?

like image 461
Adrian McCarthy Avatar asked Dec 23 '09 23:12

Adrian McCarthy


2 Answers

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 cppreference.com

like image 191
Georg Fritzsche Avatar answered Sep 22 '22 06:09

Georg Fritzsche


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

like image 34
Jesse Emond Avatar answered Sep 25 '22 06:09

Jesse Emond