Sun*_*nny 3 c++ iterator vector
我只是想问一下这里发生了什么,我哪里出错了?
vector<int> a(5);
for(int i=0; i<5; i++) cin>>a[i]; //Input is 1 2 3 4 5
for(int i=0; i<5; i++) cout<<a[i]<<" "; //Prints correct, 1 2 3 4 5
cout<<endl;
for(VI::iterator it = a.begin(); it!=a.end(); ++it) {
cout<<a[*it]<<" "; //Prints incorrect output
}
cout<<endl;
Run Code Online (Sandbox Code Playgroud)
看起来,错误输出中的最后一个元素是a[*(a.end()-1)]第一个元素,它实际上应该是缺少的.
正确的打印方式是
cout<<*it<<" ";
Run Code Online (Sandbox Code Playgroud)
*它给出了矢量指向的值.在你的情况下,[*it] = a [1]用于第一次迭代,a [2]用于第二次迭代,依此类推.最后将打印无效的号码.它是缺少第一个号码的原因.你试图打印[1] a [2],[3],a [4],