I am trying to assign values to a vector using the for each loop. If I print the values after assigning them to x
in loop 2, the order is correct.
But when I print the vector which was modified in loop 2, the vector remains unmodified. Can someone explain?
I tried using the normal for loop and then there is no problem.
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:
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(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. So when you change x (2), you change the copy of the element, and not the element in the vector.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.