C++迭代器操作

201*_*ker -1 c++ iterator

请检查注释的代码行:

#include <iostream>
#include <vector>

using namespace std;

  int main()
  {
    vector<int>numbers{1,2,3,4,5,6,7,8};
    vector<int>::iterator it, beg=numbers.begin(), end=numbers.end();

    for(it=beg; it!=end; it++){
        cout<<*it++<<endl; //THIS LINE PRINTS 1 3 5 7
    }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我正在阅读迭代器和尝试一些事情.该行似乎打印元素it引用,然后递增it.实际上它产生的结果与:

  cout<<*it<<endl;
  it++;
Run Code Online (Sandbox Code Playgroud)

我没有清楚地解释清楚,真正的问题是:你能在这样的迭代器上执行2次操作吗?

为什么*(it+1)不同*(it++)

谢谢.

Bor*_*der 6

你正在增加你的迭代器两次.一旦进入for循环" 标题 "本身:

for(it=beg; it!=end; it++){
Run Code Online (Sandbox Code Playgroud)

并且一旦进入循环

cout<<*it++<<endl;
Run Code Online (Sandbox Code Playgroud)

因此你正在跳过元素.第二行应该是:

cout<<*it<<endl;
Run Code Online (Sandbox Code Playgroud)

此外,*(it ++)与*(it + 1)不同,因为后缀运算符++返回原始值(而前缀返回递增的值).更重要的是,*(它+ 1)实际上并没有增加迭代器,使用++.让我们用一个例子来说明:

如果我有一个指向索引0处元素的迭代器:

*(it++) // will print element at index 0 and move the iterator forward to index 1
*(++it) // will move the iterator at index 1 and print element at index 1
*(it+1) // will print element at index 1, the iterator does not "move"
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到这个.