从反向迭代器获取向量中的索引 [英] Get index in vector from reverse iterator
问题描述
我知道如何通过从向量迭代器中减去开始迭代器来获取索引.例如:
I know how to get the index from a vector iterator, by subtracting the begin iterator from it. For example:
vector<int>::iterator it = find(vec.begin(), vec.end(), x);
size_t position = it - vec.begin();
但是,现在我想找到向量中最后一个x
的索引.如何从反向迭代器获取真实索引?我发现以下似乎有效的方法(无效),但也许有更好的方法(更惯用的方法或其他方法.).
However, now I want to find the index of the last x
in the vector. How can I get the real index from the reverse iterators? I've found the following that seems to work (edit: it doesn't) but maybe there is a better (more idiomatic or whatever..) way.
vector<int>::reverse_iterator it = find(vec.rbegin(), vec.rend(), x);
size_t position = vec.size() - (it - vec.rbegin());
推荐答案
我会使用:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
auto v = std::vector<int> { 1, 2, 3 };
auto rit = std::find(v.rbegin(), v.rend(), 3);
if (rit != v.rend()) {
auto idx = std::distance(begin(v), rit.base()) - 1;
std::cout << idx;
} else
std::cout << "not found!";
}
实时示例 .
在距离计算中使用-1
的原因是由于.base()
成员中反向迭代器和常规迭代器之间的转换:
The reason for the -1
in the distance computation is because of the conversion between reverse and regular iterators in the .base()
member:
24.5.1反向迭代器[reverse.iterators]
1类模板reverse_iterator是用于迭代的迭代器适配器 从其基础迭代器定义的序列的末尾到 该序列的开始.反向之间的基本关系 迭代器及其对应的迭代器i由 身份:
&*(reverse_iterator(i)) == &*(i - 1)
.
1 Class template reverse_iterator is an iterator adaptor that iterates from the end of the sequence defined by its underlying iterator to the beginning of that sequence. The fundamental relation between a reverse iterator and its corresponding iterator i is established by the identity:
&*(reverse_iterator(i)) == &*(i - 1)
.
注意:您还可以在不检查v.rend()
的情况下使用上面的代码,并使用idx == -1
等同于未找到的元素的约定.但是,这失去了执行v[idx]
的能力,因此最终您也需要对此进行检查.
Note: you could also use the above code without the check for v.rend()
, and use the convention that idx == -1
is equivalent to an element that is not found. However, that loses the ability to do v[idx]
, so eventually you would need a check against that as well.
这篇关于从反向迭代器获取向量中的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!