为什么以下代码片段会给出不同的输出?(见下面的输出)
片段1:
vector<int> v;
v.push_back(1);
v.push_back(2);
vector<int>::const_iterator iterv1=v.begin();
vector<int>::const_iterator iterv2=v.begin();
for(;iterv1!=v.end();++iterv1){
for(;iterv2!=v.end();++iterv2){
cout << "*iterv1 = " << *iterv1 << " *iterv2 = " << *iterv2 << endl;
}
}
输出:
*iterv1 = 1 *iterv2 = 1
*iterv1 = 1 *iterv2 = 2
代码片段2:
vector<int> v;
v.push_back(1);
v.push_back(2);
for(int i=0;i<2;++i){
for(int j=0;j<2;++j){
cout << "v[i] = " << v[i] << " v[j] = " << v[j] << endl;
}
}
输出:
v[i] = 1 v[j] = 1
v[i] = 1 v[j] = 2
v[i] = 2 v[j] = 1
v[i] = 2 v[j] = 2
我本来期望相同的(数字输出。显然,我对迭代器有些不了解。有人可以帮忙吗?