开发者

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

开发者 https://www.devze.com 2022-12-14 22:44 出处:网络
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.

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.开发者_C百科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?


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号