【发布时间】:2013-06-07 19:15:23
【问题描述】:
我只是想问这里发生了什么,我哪里出错了?
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;
看起来,错误输出中的最后一个元素是a[*(a.end()-1)],而第一个元素实际上应该是缺失的。
【问题讨论】:
-
输出行不应该是
cout<<*it<<" ";吗? -
而不是
a[*it],只需使用*it。原因是it是一个已经指向a中的值的迭代器。