示例:
for (vector<string>::reverse_iterator it = myV.rbegin(); it != myV.rend(); ++it)
{
cout << "current value is: " << *it << ", and current position is: " << /* */ << endl;
}
我知道我可以检查向量中有多少项,制作一个计数器,等等。但我想知道是否有更直接的方法来检查当前索引而不断言我得到了向量的长度。
答案 0 :(得分:2)
vector Iterators支持difference你可以从rbegin中减去当前迭代器。
修改的
如注释中所述,并非所有迭代器都支持operator-所以必须使用std :: distance。但是我不建议这样做,因为std :: distance会导致非随机访问的迭代器的线性时间性能成本,而如果你使用it - begin()
,编译器会告诉你这不会起作用然后你可以使用距离如果你必须的话。
答案 1 :(得分:1)
从当前迭代器中减去std::vector<T>::begin()
(或你的rbegin()
)。这是一个小例子:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> x;
x.push_back(1);
x.push_back(1);
x.push_back(3);
std::cout << "Elements: " << x.end() - x.begin();
std::cout << "R-Elements: " << x.rend() - x.rbegin();
return 0;
}
正如上面的一个非常好的评论所指出的,std::distance
可能是更好的选择。 std::distance
在常量时间内支持随机访问迭代器,但在线性时间内也支持其他类别的迭代器。
答案 2 :(得分:1)
迭代器用于允许编写对容器选择不变的泛型算法。我在STL Book中读到这很好,但可能导致性能下降,因为有时容器的成员函数针对容器进行了优化,并且运行速度比依赖于迭代器的通用代码运行得更快。在这种情况下,如果你正在处理一个大向量,你将调用std :: distance,虽然不需要常量。如果你知道你将使用oly vector作为这个算法,你可能会认识到它支持直接访问运算符“[]”并写下这样的东西:
#include <vector>
#include <iostream>
using namespace std;
int main ()
{
vector<int> myV;
for (int I = 0; I < 100; ++I)
{
myV.push_back(I);
}
for (int I = 0; I < myV.size(); ++I)
{
cout << "current value is: " << myV[I]
<< ", and current position is: " << I << endl;
}
return 0;
}
如果您对速度感兴趣,可以随时尝试此处提出的不同答案并测量执行时间。它可能取决于矢量大小。
答案 3 :(得分:0)
保留一个柜台:
for (vector<string>::reverse_iterator it = myV.rbegin(),
int pos = myV.size;
it != myV.rend(),
--pos;
++it)
{
cout << "current value is: " << *it << ", and current position is: " << pos << endl;
}