【发布时间】:2011-12-16 10:38:32
【问题描述】:
我有一个 std::vector,为了简单起见,我们说整数。
std::vector<int> ivec;
ivec.push_back(1);
ivec.push_back(2);
... //omitting some push back's 3 to 99
ivec.push_back(100);
标准的迭代方式是已知的
std::map<int>::iterator it;
for( it = ivec.begin(); it != ivec.end(); it++ )
print();
该迭代将打印 1,2,3, ... 100。
我想遍历从预定义索引开始的所有向量元素,而不是从 it.begin() 开始。 我想打印
3,4,5,6 ... 99, 100, 1, 2
你能在这里分享你的想法吗?
分两步就可以了
for( it = ivec.begin()+index; it != ivec.end(); it++ ) and then (if index !=0)
for ( it = ivec.begin; it = it = ivec.begin() + (index-1); it++)
【问题讨论】:
-
您可以编写一个迭代器包装器来显示所需的行为。但是,除非您需要多次,否则它可能是矫枉过正。
-
查看 Boost 循环缓冲区:boost.org/doc/libs/1_48_0/libs/circular_buffer/doc/…
-
你的最后一个例子是错误的。在第二个循环中,条件应该是
it != ivec.begin()+index(当然,这仅适用于随机迭代器)并且您不需要if index != 0,循环条件会为您完成。