My program should use the function find_if() to find the odd numbers in the vector and add a -1 in front of them, for some reason I'm getting an error?
You find an odd number
... then insert a -1 in front of it
... so that your iterator now points to the -1
... which is odd
... so you put a -1 in front of that
... and again
... and again
until your code gives up.
You would have to move two places forward after insertion.
One way would be changing v.insert(p,-1);
to {v.insert(p,-1); p+=2; }
but it looks horrible and may or may not be portable.
BTW, you are inserting a -1, not deleting odd numbers as implied by line 28. If you want to erase odd numbers use the erase-remove idiom (or erase-remove_if here). v.erase( remove_if( v.begin(), v.end(), odd ), v.end() );
try this
if(p!= v.end())
{
v.insert(p,-1);
p+=2; //move p past the inserted 1 and past the value it found. it keeps finding the same value until it runs out of memory.
}
did you know that you could just insert the -1s as you build the vector? generate a random value, if its odd, insert a -1 then insert it, else ... if that makes sense in the bigger picture of whatever this is for (if there is anything more) ...
If a reallocation happens, all iterators, pointers and references related to the container are invalidated.
Otherwise, only those pointing to position and beyond are invalidated, with all iterators, pointers and references to elements before position guaranteed to keep referring to the same elements they were referring to before the call.
Return value
An iterator that points to the first of the newly inserted elements.
I missed the iterator invalidation as well, good catch indeed. I even saw the symptoms of this and missed it /blush .. I saw it adding random values to the array (before the p+=2) after it had added enough -1s to it to make it resize, and didnt connect the dots.
I still hate iterators lol. Its like someone hated pointers so much, they made something worse.
Hiding paradigm... Ive seen a lot of times when people dislike something unavoidable, they hide it behind an interface... which is exactly what iterators are doing.