push_back while iterating

Hi
I have a program which gives me an assertion error when tries to push_back some value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
using namespace std;

int main(){
	int n;
	vector<int> v;
	vector<int>::iterator it;
	v.push_back(5);
	v.push_back(9);
	v.push_back(23);
	while(true){
		cin>>n;
		for(it=v.begin(); it!=v.end(); it++){
			if((*it)==n) v.push_back(n+1);
		}
	}
	return 0;
}

Help please
Inserting into a vector I believe invalidates iterators because iterators are nothing more than pointers, and if the vector gets reallocated all iterators (pointers) will now be dangling.

If you do not want to invalidate iterators, try using list instead. Otherwise you will need to make significant modification to your code.
first, i understand it may just have been for the purposes of this, however, it is never a good idea to get in the habit of writing infinite loops. also, i think smith is right, but you should still be able to use a vector doing this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <vector>
using namespace std;

int main(){
	int n;
        bool someValue = true;
	vector<int> v;
	v.push_back(5);
	v.push_back(9);
	v.push_back(23);
	while(someValue){
		cin>>n;
                int i;
                int size = v.size();
		for(i=0; i < size; i++){
		       if(v[i] == n)
                       {
                           v.push_back(n+1);
                           size++;
                           // or size = v.size() again to be safe...
                       }
		}
                if(someExpression)
                {
                   someValue = false;
                }
	}

        // just for testing, this loop prints the final contents of the vector
        int i, s = v.size();
        for(i = 0; i < s; i++)
        {
             cout<<v[i];
        }
        system("pause");

	return 0;
}


edit: the following statement is only true when you change "someExpression" to a valid c/c++ boolean expression!
this compiles and seems to run without any problems. i don't know if this will work for you, but i think that this would be a good way to do it.

one of the things that i love about vectors is the ability to access them just like standard C arrays. if you want to be extra sure you don't try to access an out of bounds element, just use the ".at(int n)" member of the vector to specify the number element you want a reference to.
Last edited on
it may look like a lot more code, but it's mostly just a few variable initializations and i like to space out my code to make it more readable... plus i added the printout at the end...
Topic archived. No new replies allowed.