使用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的::基地()
是你在找什么 - 上的韶钢松山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
相关推荐
最新文章