Difference between erase and remove

c++, stl

Solution

`remove()` doesn't actually delete elements from the container -- it only shunts non-deleted elements forwards on top of deleted elements. The key is to realise that `remove()` is designed to work on not just a container but on any arbitrary forward iterator pair: that means it can't actually delete the elements, because an arbitrary iterator pair doesn't necessarily have the ability to delete elements.

For example, pointers to the beginning and end of a regular C array are forward iterators and as such can be used with `remove()`:

int foo[100];

...

remove(foo, foo + 100, 42);    // Remove all elements equal to 42

Here it's obvious that `remove()` cannot resize the array!

Problem

I am bit confused about the difference between the usage of std::remove algorithm. Specifically I am not able to understand what is being removed when I use this algorithm. I wrote a small test code like this: ``` std::vector<int> a; a.push_back(1); a.push_back(2); std::remove(a.begin(), a.end(), 1); int s = a.size(); std::vector<int>::iterator iter = a.begin(); std::vector<int>::iterator endIter = a.end(); std::cout<<"Using iter...\n"; for(; iter != endIter; ++iter) { std::cout<<*iter<<"\n"; } std::cout<<"Using size...\n"; for(int i = 0; i < a.size(); ++i) { std::cout<<a[i]<<"\n"; } ``` The output was 2,2 in both the cases. However, if I use erase with the remove something like this: ``` a.erase(std::remove(a.begin(), a.end(), 1), a.end()); ``` I get the output as 2. So my questions are: (1). Is there any use of std::remove other than using it with erase function. (2). Even after doing std::remove, why a.size() returns 2 and not 1? I read the item in Scott Meyer's Effective STL book about the erase-remove idiom. But am still having this confusion.

Original source