deque and iterator += ###
hello,
I have this code:
#include <iostream>
#include <deque>
using namespace std;
int main()
{
deque<int> q;
deque<int>::iterator it = q.begin();
for( int i =0; i < 1000; i++ ) q.push_back( i );
it += 850;
cout << "Here it's running" << endl;
cout << *it << endl;
cout << "Here not" << endl;
return 0;
}
but when I run this program, the result is:
Here it's running
SIGSEGV
Could somebody explain me why it doesn't work? Do I have to every time, I've changed the deque, reinitialize the iterator?!
thanks
[701 byte] By [
jaa] at [2007-11-11 10:06:00]

# 1 Re: deque and iterator += ###
I think its a one time problem, try just pushing one item or simply reserving some memory for the q, then get the begin, and it should stick.
jonnin at 2007-11-11 20:59:24 >

# 2 Re: deque and iterator += ###
it+850 doesn't do what you probably think it does. It increments the *address*, not the value stored in *it. You probably want to do this:
*it+-850;
But even this will not work since it is assigned q.begin();before you insert any elements to the queue. Thus, *it is like dereferencing a NULL pointer.
If you want to increment a specific queue element, best to a local iterator instead:
deque<int> q;
deque<int>::iterator it;
for( int i =0; i < 1000; i++ ) q.push_back( i );
it=q.begin();
*it += 850;
Danny at 2007-11-11 21:00:29 >

# 3 Re: deque and iterator += ###
I've tried to add some items at the end of the deque before creating the iterator but it makes no difference.
I really wanted to increase the address of the iterator not his value.
And I need to have an iterator of the deque pointing to a particular item in the deque but the deque can grow.
jaa at 2007-11-11 21:01:34 >

# 4 Re: deque and iterator += ###
OK, so you wanted to increment the interator by the offset 850 elements. In that case, yoru code is still wrong. The problem is that the loop causes the deque to reallocate storage. Reallocation invalidates the original iterator so when you increment it, you get an invalid address. This code should work, though:
deque<int> q;
deque<int>::iterator it;
for( int i =0; i < 1000; i++ ) q.push_back( i );
it=q.begin();
it += 850;
BTW, you don't an iterator object for this:
cout << *(q.begin()+850) <<endl;
Does the trick, too, without the risk of using an invalid iterator.
Remember: a push_back() call (or any other non-const member function call) might invalidate an iterator that was assigned before the call so you must either use a fresh iterator after each call, or call reserve(1000) before the loop.
You can learn more about container reallocation and how it affects iterators here: http://www.dev-archive.com/tips/Tip/12887
Danny at 2007-11-11 21:02:34 >
