是否有 STL 算法来查找序列中值的最后一个实例?

2022-01-20 00:00:00 algorithm find c++ stl

使用 STL,我想在一个序列中找到某个值的最后一个实例.

Using STL, I want to find the last instance of a certain value in a sequence.

此示例将在整数向量中找到 0 的 第一个实例.

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);

现在我可以使用 split 来处理子范围 begin() .. splitsplit.. end().我想做类似的事情,但将拆分设置为 0 的 last 实例.我的第一直觉是使用反向迭代器.

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);

这不起作用,因为 split 是错误的迭代器类型.所以...

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);

但现在的问题是我不能像 begin(), splitsplit, end() 这样的头"和尾"范围,因为那些不是反向迭代器.有没有办法将反向迭代器转换为相应的正向(或随机访问)迭代器?有没有更好的方法来查找序列中元素的最后一个实例,以便留下兼容的迭代器?

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?

推荐答案

但现在的问题是我不能使用头"和尾"范围begin() 和 end() 因为它们不是反向迭代器.

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() 是您正在寻找的 - 新成员 部分/stl/ReverseIterator.html" rel="noreferrer">SGI reverse_iterator 描述 或 在 cppreference.com 上

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

相关文章