Iterator _ erasing from a vector help

This is a discussion on Iterator _ erasing from a vector help within the C++ Programming forums, part of the General Programming Boards category; I have a user created struct (named Nze), composed of int x co-ordinate, int y co-ordintate, and int a_value. A ...

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    104

    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.

    Code:
    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 ;
    
     	 result.nze.erase(it-1);
     
       }
    it++;
    }
    


  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,340
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21