我想遍历向量中所有相邻对元素。例如,如果我有一个vector {1, 2, 3, 4},我希望我的迭代器返回以下内容:
(1, 2)
(2, 3)
(3, 4)
Run Code Online (Sandbox Code Playgroud)
我知道如何使用以下方法一次遍历一个元素:
(1, 2)
(2, 3)
(3, 4)
Run Code Online (Sandbox Code Playgroud)
但是我也不知道如何获得下一个要素。
std::vector::iterator几乎可以像指针一样使用。
确保循环的条件已更改并*(it+1)在循环中使用。
vector<int> numbers = {1, 2, 3, 4}; // One =, not two.
// If the vector is empty, skip the block.
if ( !numbers.empty() )
{
vector<int>::const_iterator end = numbers.cend() - 1;
for (vector<int>::const_iterator it = numbers.cbegin(); it != end; ++it) {
cout << '(' << *it << ',' << *(it+1) << ')' << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
工作演示。