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!
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With