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:
#include <iostream>
#include <vector>
usingnamespace 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.
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...