是否有一个STL算法来寻找序列中值的最后一个实例? [英] Is there an STL algorithm to find the last instance of a value in a sequence?

查看:206
本文介绍了是否有一个STL算法来寻找序列中值的最后一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这个例子会发现在整数的向量中的第一的0实例。

 的#include<算法>
#包括<迭代器>
#包括<载体>

类型定义的std ::矢量< INT> INTVEC;
INTVEC值;
// ...整数加到值
INTVEC ::常量性拆分=的std ::发现(values​​.begin(),values​​.end(),0);
 

现在我可以使用分割来做事的子范围开始() .. 分割分割 .. 端()。我想要做类似的事情,但与分裂设置为最后的0。例如我的第一反应是使用反向迭代器。

  INTVEC ::为const_iterator分裂=的std ::发现(values​​.rbegin(),values​​.rend(),0);
 

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

  INTVEC ::拆分为const_reverse_iterator =的std ::发现(values​​.rbegin(),values​​.rend(),0);
 

但现在的问题是,我不能做头和尾的范围,比如开始(),分割分裂,结束(),因为这些都无法扭转的迭代器。有没有一种方法来反向迭代器转换为相应的进(或随机访问)迭代器?有没有更好的方法来找到序列中的一个元素的最后一个实例让我留下了一个兼容的迭代器?

解决方案
  

但现在的问题是,我不能   使头和尾的范围使用   开始()和end(),因为这些都不是   反向迭代器。

reverse_iterator的::基地()是你在找什么 - 上的新成员的:// WWW .sgi.com /技术/ STL / ReverseIterator.html相对=nofollow>韶钢松山reverse_iterator的描述或的在这里CP preference.com

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?

解决方案

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

这篇关于是否有一个STL算法来寻找序列中值的最后一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆