Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ : unsequenced modification and access to "i"

Tags:

c++

My ideas were quite simple. I wish to copy element by element from vector temp to vector data.

void copy(vector<int> &data, vector<int> &temp)
{    
    int i=0;
    while (i<data.size()) {
    data[i]=temp[i++];//unsequenced modification and access to "i"
    cout<<i<<endl;
}

Outputs: temp={1,2,3,4} but data={1,1,2,3} even if i's cout values are 1,2,3,4

wonder why. Thanks for help in advance!

like image 979
Genie Avatar asked Nov 16 '15 19:11

Genie


1 Answers

The line

data[i]=temp[i++];//unsequenced modification and access to "i"

has undefined behavior. The result of executing the line will be different depending on whether data[i] is evaluated first or temp[i++] is evaluated first.

Use

while (i<data.size()) {
    data[i]=temp[i];
    ++i;
}

As an alternative, use the std::copy function.

void copy(vector<int> &data, vector<int> &temp)
{
   std::copy(temp.begin(), temp.end(), data.begin());
}
like image 149
R Sahu Avatar answered Oct 19 '22 18:10

R Sahu