Thread: Iterator _ erasing from a vector help

  1. #1
    Registered User
    Join Date
    Oct 2003

    Iterator _ erasing from a vector help

    I have a user created struct (named Nze), composed of int x co-ordinate, int y co-ordintate, and int a_value. A series of these structs have been inserted into a vector (named result) which was already sorted and may contain duplicates (the same x and y co-ordinates) If there is a duplicate I want to be able to add the two "duplicate" a_value together in one of the structures and delete the other adjacent one. I tired this code but it is crashing on run time all the time.

    typedef vector<Nze>::iterator vit;
    vit it = result.nze.begin()+1;
    while (it != result.nze.end() ){
       if (equalPosition(*it,*(it-1))) {
    	 (*it).a_value  += *(it-1).a_value ;

  2. #2
    Registered User
    Join Date
    Jan 2005
    Once you erase a value, its iterator is invalid. Assign the return value of erase to it, it will be the next correct iterator. Then put the increment of it into an else block since you only want to increment with ++ if you don't erase.

Popular pages Recent additions subscribe to a feed