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

帅比萌擦擦* 提交于 2019-12-18 12:50:02

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/1955885/is-there-an-stl-algorithm-to-find-the-last-instance-of-a-value-in-a-sequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!