简体   繁体   English

使用基于范围的for循环将值分配给矢量

[英]Assigning values to a vector using a range-based for-loop

I am trying to assign values to a vector using the for each loop. 我正在尝试使用for each循环为向量赋值。 If I print the values after assigning them to x in loop 2, the order is correct. 如果在将值分配给循环2中的x后打印值,则顺序正确。

But when I print the vector which was modified in loop 2, the vector remains unmodified. 但是当我打印在循环2中修改的向量时,向量保持不变。 Can someone explain? 谁能解释一下?

I tried using the normal for loop and then there is no problem. 我尝试使用正常for循环,然后没有问题。

The code that doesn't work: 代码不起作用:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> a = { -1, 150, 190, 170, -1, -1, 160, 180 };
    vector<int> v;

    // loop 1
    for (int x : a)
    {
        if (x != -1)
            v.push_back(x);
    }
    sort(v.begin(), v.end(), greater<int>());

    // loop2
    for (int x : a)
    {
        if (x != -1)
        {
            x = v.back();
            v.pop_back();
            cout << x << " ";
        }
        else
            cout << x << " ";
    }

    cout << endl << endl;

    // loop3
    for (int x : a)
        cout << x << " ";
}

The code works when loop 2 is replaced by: 当循环2被替换为以下代码时,代码有效:

for (int x = 0; x < a.size(); x++)
{
    if (a[x] != -1)
    {
        a[x] = v.back();
        v.pop_back();
    }
}

Actual result: 实际结果:

-1 150 160 170 -1 -1 180 190

-1 150 190 170 -1 -1 160 180

Desired result: 期望的结果:

-1 150 160 170 -1 -1 180 190

-1 150 160 170 -1 -1 180 190

The problem is in the for loop: 问题出在for循环中:

for(int x:a) { // (1)
    if(x!=-1)
    {   
        x=v.back(); // (2)
        v.pop_back();
        cout<<x<<" ";}
    else
        cout<<x<<" ";
}

x is a copy of the element in a, and not the element directly. x是a中元素的副本 ,而不是元素的副本 So when you change x (2), you change the copy of the element, and not the element in the vector. 因此,当您更改x(2)时,您将更改元素的副本,而不是向量中的元素。

If you want to change the elements in the vector, do 如果要更改向量中的元素,请执行

for(int& x : a)

then x will be a reference to the element in a, and when x if changed, the corresponding element in a is changed as well. 那么x将是对a中元素的引用 ,当x如果改变时,a中的对应元素也会被改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM