What is the explanation for the behavior of it++
and ++it
in the context of a function call--and more specifically, for the function iter_swap
? It confuses me that call 2 and call 4 in the code below appear to swap the elements, whereas call 3 and call 5 fail to swap elements. I expected the opposite result, however, I was assuming that one of the entries to the function parameters would execute before the other. Looking at the output, this appears not to be the case.
So, out of curiosity, is this behavior defined? How can I make sense of the order in which things execute? Thanks!
#include <iostream>
#include <vector>
#include <algorithm>
int main(void) {
vector<int> a;
a.push_back(1);
a.push_back(2);
vector<int>::iterator it_a, it_b;
it_a = a.begin();
it_b = it_a + 1;
cout << *it_a << " " << *it_b << endl;
// call 1
iter_swap(it_a, it_b);
cout << *it_a << " " << *it_b << endl;
// call 2
iter_swap(it_a, it_a++);
cout << *--it_a << " " << *it_b << endl;
// call 3
iter_swap(it_a, ++it_a);
cout << *--it_a << " " << *it_b << endl;
// call 4
iter_swap(it_a++, it_a);
cout << *--it_a << " " << *it_b << endl;
// call 5
iter_swap(++it_a, it_a);
cout << *--it_a << " " << *it_b << endl;
return 0;
}
outputs:
1 2
2 1
1 2
1 2
2 1
2 1