Is there an STL algorithm to find the last instance of a value in a sequence?(是否有 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() .. split 和 split.. 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(), split 和 split, 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
这篇关于是否有 STL 算法来查找序列中值的最后一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否有 STL 算法来查找序列中值的最后一个实例
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
