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 算法来查找序列中值的最后一个实例
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- c++ STL设置差异 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
