I'm trying to 'reduce' a vector using the erase algorithm within a for loop.
The idea is to scan a table looking for equal successive elements. Once equal elements are found, it erases one of the 2 elements. I'm suspecting a problem in the for loop, due to the iterator. What happens to it's value once an element is deleted ?
Because vectors keep an array format, erasing on positions other than the vector end also moves all the elements after the segment erased to their new positions,
This invalidates all iterator and references to elements after position or first.
>>What happens to it's value once an element is deleted ?
The iterator is invalidated and you have to start it all over again. Example here: The program will crash after the erase() is executed unless the break statement is there to stop the loop.
I admit my question was silly! :confused:
I tried it, but it didn't work.
Actually, it compiles, but then the pc starts WORKING HARD(calculating?), and don't stop until I force it to quit.
Would you please help me find the error?
if you want to iterate through a sequence container erasing elements as you go along, you must use the return value of container::erase . the return value is a vald iterator that designates the first element remaining beyond element(s) erased, or end if no such element exists. for example, the following will erase all even numbers from the vector.
std::vector<int> vec(100) ;
for( int i=0 ; i<vec.size() ; ++i ) vec[i] = i ;
std::vector<int>::iterator iter = vec.begin() ;
while( iter != vec.end() )
if( ( *iter % 2 ) == 0 ) iter = vec.erase( iter ) ;
else ++iter ;
to remove duplicate elements that are adjacent to each other in a specified range, you can use the algorithm std::unique . for example, this will erase adjacent duplicate elements from the vector.