4

Possible Duplicate:
Difference between erase and remove

suppose i have a container.... what does the following mean.

c.erase(remove(c.begin(),c.end(),99),c.end());

aren't erase and remove the same? What is the specific function of erase and remove in the above example?

Community
  • 1
  • 1
Saikiran
  • 143
  • 2
  • 7
  • 5
    Look up the erase remove-idiom. I know it's on here somewhere. Basically, algorithms have no knowledge of the container they're working on, so actually erasing them is impossible. – chris Dec 14 '12 at 07:51
  • 1
    I can't believe it's not a duplicate. – Christian Rau Dec 14 '12 at 08:39

1 Answers1

10

It removes all elements equal to 99 from container c.

std::remove doesn't actually remove any elements. It moves all the elements of interest to the second part of the container, and returns an iterator indicating the first of these. Then the erase member function takes an iterator range to actually remove the elements from the container.

See erase-remove idiom.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • can we write the code something like this? c.erase(c.begin(),c.end(),99); – Saikiran Dec 14 '12 at 09:19
  • @Saikiran No, but in general, you have to look at the interface of each container. You can certainly not do it with `std::vector`, `std::deque` and `std::list`. These all require either one iterator, or two, specifying a range of elements to be deleted. – juanchopanza Dec 14 '12 at 09:25
  • @juanchopanza In fact you *can* do it with `std::list`, just not with `erase`, but `list.remove(99)`, which might be a better choice over *erase-remove*'s optimization for block erasure that doesn't buy you anything for a list. – Christian Rau Dec 14 '12 at 09:51