2

Consider the code:

list<int> a{ 4,3,1,2 }; auto i = a.begin(); swap(*i, *(++i)); 

Why does the swap do nothing? While the following works as expected?

list<int> a{ 4,3,1,2 }; auto i = a.begin(); swap(*i, *(next(i))); 
3
  • Why do you think that it does nothing? Commented Aug 17, 2020 at 15:18
  • @eerorika the evaluation order of parameters is very much compiler dependent, so they may get different results than you do. Commented Aug 17, 2020 at 15:22
  • 1
    There is a simpler way to swap: std::iter_swap(i, std::next(i)) Commented Aug 17, 2020 at 15:29

1 Answer 1

6

In the first code, the order of evaluation of the two ops *i and *(++i) unspecified after c++17, hence the second one may execute before the first, and then the swapping swaps two equivalent values.

In the attached link, u can see that

f(++i, ++i); // undefined behavior until C++17, unspecified after C++17

But in the second code you have different parameters and std::next() returns a new iterator.

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.