# Iterator algorithm: assignment

• Dears,

Is it possible to assign an iterator to another one? With the following code I want to test it. But nothing will be printed except "vector filled".

``````#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> ivec;
for (int i=0; i<10; ++i)
ivec.push_back(i);
cout << "vector filled" << endl;
vector<int>::const_iterator iter;
vector<int>::const_iterator itermemo;
for (iter = ivec.begin(); iter != ivec.end(); ++iter) {
if ((*iter) == 3) itermemo = iter;
++iter;
}
iter = itermemo;
do {
--iter;
cout << *iter << endl;
} while (iter != ivec.begin());
//iter = itermemo;
for (iter = itermemo; iter != ivec.end(); ++iter) {
cout << *iter << endl;
++iter;
}
return 0;
}
``````

• Because itermemo is not initialized at all and you don't check for iter != ivec.begin() before dereferencing the iterator in your second loop.
Why it's not initialized at all is a task for you, simply inspect the first loop.

/edit: same mistake in the third loop.

• Dear Christian,

ivec contains 0 through 9, and with " if ((*iter) == 3) itermemo = iter;" itermemo must be initialized, if the syntax is correct. I expect the output 2 through 0 with the do loop and 3 through 9 in the last loop.

• itermemo must be initialized,

No, please take a look on what you're doing with iter in your first and last loop.

• @Weichao-Wang
Oh, I've found the problem. In the last two for loops I've repeated ++iter, which leads to the result that *iter == 3 would never be encountered. Thank you!

• This post is deleted!

• double instead of doppelt (which is German).

You can edit your posts by clicking on the three vertical dots right down of the post.
And when the topic is solved you can mark it as such with the 'Topic Tools' button.