gfever
gfever

Reputation: 13

Why is this swap method not working?

Why does the below two snippets of code have different results? I want to add a 1 in front of digits, which is a vector of integers. But the second snippet does not properly swap.

int tmpInt(1);
for (int i=0; i<digits.size(); i++){
    swap(tmpInt, digits[i]);
}
digits.push_back(tmpInt);

versus:

int tmpInt(1);
for (auto it : digits){
    swap(tmpInt, it);
}
digits.push_back(tmpInt);

Upvotes: 0

Views: 58

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118300

for (auto it : digits){

The range variable gets essentially copied by value, from the sequence, so

   swap(tmpInt, it);

all this is doing is swapping between tmpInt and a temporary range variable.

You need to use a reference, in order to get equivalent results with the first example:

for (auto &it : digits){
   swap(tmpInt, it);

Upvotes: 4

Related Questions