我正在测试向量到向量初始化,我使用基于范围的for循环它给出了不同的输出。
关于Normal for loop。
vector<int> intVector;
for(int i = 0; i < 10; i++) {
intVector.push_back(i + 1);
cout << intVector[i] << endl;
}
cout << "anotherVector" << endl;
vector<int> anotherVector(intVector);
for(auto i : anotherVector)
cout << anotherVector[i] << endl;
//for(unsigned int i = 0; i < anotherVector.size(); i++) {
// cout << anotherVector[i] << endl;
//}
这个基于for循环的范围给出了输出 - Linux ubuntu
输出
STLTest Cunstructor Called.
1
2
3
4
5
6
7
8
9
10
anotherVector
2
3
4
5
6
7
8
9
10
81
2
vector<int> intVector;
for(int i = 0; i < 10; i++) {
intVector.push_back(i + 1);
cout << intVector[i] << endl;
}
cout << "anotherVector" << endl;
vector<int> anotherVector(intVector);
//for(auto i : anotherVector)
// cout << anotherVector[i] << endl;
for(unsigned int i = 0; i < anotherVector.size(); i++) {
cout << anotherVector[i] << endl;
}
这会产生不同的输出。
输出
STLTest Cunstructor Called.
1
2
3
4
5
6
7
8
9
10
anotherVector
1
2
3
4
5
6
7
8
9
10
为什么for循环的行为不同?
答案 0 :(得分:11)
for(auto i : anotherVector)
cout << anotherVector[i] << endl;
此代码不符合您的想法。基于范围的for循环遍历值,而不是索引。换句话说,循环变量(i
)被分配给向量的所有元素转动。
要复制第一个循环的功能,您需要:
for (auto i : anotherVector)
cout << i << endl;
您的原始代码正在做的是获取向量的元素,并使用它再次索引到向量。这就是数字偏离一个原因(因为向量在位置n + 1
处保持数字n
)。然后,最终输出(在你的情况下为81)实际上是随机的,并且是未定义行为的结果 - 你已经越过了向量的末尾。