使用 STL,我想在一个序列中找到某个值的最后一个实例。
此示例将在整数 vector 中找到 0 的 第一个实例。
#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()
.. split
和 split
.. end()
。我想做类似的事情,但将拆分设置为 0 的 last 实例。我的第一直觉是使用反向迭代器。
intvec::const_iterator split = std::find(values.rbegin(), values.rend(), 0);
这不起作用,因为 split
是错误的迭代器类型。所以...
intvec::const_reverse_iterator split = std::find(values.rbegin(), values.rend(), 0);
但现在的问题是我不能像 begin(), split
和 split, 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()
是您正在寻找的 - SGIs reverse_iterator description 上的 新成员 部分或 here on cppreference.com
关于c++ - 是否有 STL 算法来查找序列中值的最后一个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1955885/