std::vector erase() not working as intended

3314 views c++
7

I'm trying to erase specific elements from a vector of OrderPair while iterating, but it doesn't work as I expect it to. I'm trying to delete every OrderPair with id (first) that equals customer_Id. I do the following:

for(std::vector<OrderPair>::iterator i = source_Orders.begin(); i != source_Orders.end();)
{
      if((*i).first == customer_Id)
      {
          dest_Orders.push_back(*i);
          i = source_Orders.erase(i);
      }
      else
      {
          i++;
      }
 }
// definition of OrderPair
typedef std::pair<int, Dish> OrderPair;
// definition of OrderPair
enum DishType{
    VEG, SPC, BVG, ALC
};
// definition of OrderPair
class Dish{
private:
    const int id;
    const std::string name;
    const int price;
    const DishType type;
};

When the iterator is pointing at an element that fits the if condition, (I can see when debugging that it points to the correct element), the command dest_Orders.push_back(*i); is working as intended, then I'm trying to erase the element which I moved to dest_Orders, and keep going with the next iteration. However, the result is a removal of the last element in the vector source_Orders.

What am I doing wrong here?

Thanks in advance.

answered question

1 Answer

9

There's something you are not showing us.

class Dish{
private:
    const int id;
    const std::string name;
    const int price;
    const DishType type;
};

I'm guessing that you originally got an error saying that you can't assign Dish because the members are const. So you added an assignment operator that does nothing. Yay, it now compiles.

Unfortunately, vector depends on the assignment operator actually doing what it says on the tin, because it uses assignment to move the elements around when you erase something in the middle.

posted this

Have an answer?

JD

Please login first before posting an answer.