Consider the following piece of code:
1 typedef std::deque<int> mydeque_t;
2 mydeque_t mydeque;
3
4 mydeque_t::iterator start = mydeque.begin();
5
6 for (int i = 0; i != 1000; ++i)
7 mydeque.push_back(i);
8
9 for (mydeque_t::iterator myint = start; myint != mydeque.end(); ++myint)
10 *myint += 1;
When executing it I always get a runtime error on line 10 (live example: http://ideone.com/juQAA). However when I change line 6 to for (int i = 0; i != 100; ++i) the code works fine.
The code would easily be fixed by moving the start definition (line 4) behind the first for loop, but in my example I need it to stay before it. However even like this I think it should run fine, can anyone explain to me why it does not?
After a call to push_back(), all iterators are invalidated. From deque::push_back():
Appends the given element value to the end of the container. All iterators are invalidated. No references are invalidated.
Guess: The code probably works fine with 100 and not 1000 as the internal storage of the deque did not have to be reallocated to accomodate the 100 elements resulting in the begin() iterator remaining valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With