【问题标题】:vectors in range based for loop基于范围内的向量 for 循环
【发布时间】:2016-06-06 11:16:23
【问题描述】:

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

关于正常的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 循环给出了输出 - 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 循环的行为不同?

【问题讨论】:

    标签: c++ for-loop vector range


    【解决方案1】:
    for(auto i : anotherVector)
        cout << anotherVector[i] << endl;
    

    此代码并没有按照您的想法执行。基于范围的 for 循环迭代 值, 而不是 索引。 换句话说,循环变量 (i) 依次分配了向量的所有元素。

    要复制第一个循环的功能,您需要这样:

    for (auto i : anotherVector)
        cout << i << endl;
    

    您的原始代码所做的是获取向量的一个元素,并使用它再次对向量进行索引。这就是为什么数字相差 1 的原因(因为向量在位置 n 处持有数字 n + 1)。然后,最终输出(在您的情况下为 81)实际上是随机的,并且是 Undefined Behaviour 的结果——您已经超过了向量的末尾。

    【讨论】:

    • 谢谢,它是根据我自己的价值观旋转的。
    猜你喜欢
    • 2020-05-03
    • 2016-10-31
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多