C++ 基于范围的for循环向量

C++ 基于范围的for循环向量,c++,for-loop,vector,range,C++,For Loop,Vector,Range,我在测试向量到向量的初始化,我使用了基于范围的循环,它给出了不同的输出 相对于正常的for循环 vector<int> intVector; for(int i = 0; i < 10; i++) { intVector.push_back(i + 1); cout << intVector[i] << endl; } cout << "anotherVector" << endl; vector<in

我在测试向量到向量的初始化,我使用了基于范围的循环,它给出了不同的输出

相对于正常的for循环

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循环的行为不同

for(auto i : anotherVector)
    cout << anotherVector[i] << endl;
您的原始代码所做的是获取向量的一个元素,并使用它再次索引到向量中。这就是为什么这些数字相差1,因为向量在n的位置上保持了n+1。然后,您案例中的最终输出81实际上是随机的,并且您到达的未定义行为的结果超过了向量的末尾


您的原始代码所做的是获取向量的一个元素,并使用它再次索引到向量中。这就是为什么这些数字相差1,因为向量在n的位置上保持了n+1。然后,在您的情况下,最终输出81实际上是随机的,并且您到达的未定义行为的结果超过了向量的末尾。

谢谢,它是基于I本身的值旋转的。谢谢,它是基于I本身的值旋转的。
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(auto i : anotherVector)
    cout << anotherVector[i] << endl;
for (auto i : anotherVector)
    cout << i << endl;