samedi 15 juin 2019

is there a problem with assigning values to a vector by using for each loop?

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;
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

Aucun commentaire:

Enregistrer un commentaire