0

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); 
2
  • Rhetorical: int x = 6; int y = x; y = 4; // why is x still 6 instead of 4???? Commented Mar 2, 2017 at 2:40
  • I think "it" is not an iterator so maybe you want to change the name Commented Mar 2, 2017 at 3:42

1 Answer 1

4
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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.