Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "L.insert(it--, i);" behave differently from "L.insert(it, i); it--;"?

Tags:

c++

std

These are two pieces of code that I ran under the C++11 standard. I expected the post-decrement of the iterator to produce the same effect, but these two pieces of code produce completely different results. Where is my understanding off?

list<int> L;

int main() {    
    L.push_back(0);
    L.push_front(1);
    auto it = L.begin();
    for (int i = 2; i <= 5; i++) {
        L.insert(it--, i);
    }
    for (auto num : L) {
        printf("%d ", num);
    }
    // 2 5 0 4 1 3
}
list<int> L;

int main() {    
    L.push_back(0);
    L.push_front(1);
    auto it = L.begin();
    for (int i = 2; i <= 5; i++) {
        L.insert(it, i);
        it--;
    }
    for (auto num : L) {
        printf("%d ", num);
    }
    // 5 4 3 2 1 0
}
like image 679
LYFer Avatar asked Oct 15 '25 19:10

LYFer


1 Answers

L.insert(it, i);
it--;

This inserts a node before it, then moves it backwards to the inserted node.

L.insert(it--, i);

The order of operations is swapped: it moves the iterator backwards before insert() is called. There's no node to move back to so it causes undefined behavior.

like image 98
John Kugelman Avatar answered Oct 17 '25 10:10

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!