why doesn't std::remove_copy_if() actually remove?

Viewed 7578

Could this be the worst named function in the STL? (rhetorical question)

std::remove_copy_if() doesn't actually appear to do any removing. As best I can tell, it behaves more like copy_if_not.

The negation is a bit confusing, but can be worked around with std::not1(), however I might be misunderstanding something as I cannot fathom what this function has to do with removing - am I missing something?

If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container?

Editing to add an example so readers are less confused.

The following program appears to leave the input range (V1) untouched:

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

using std::cout;
using std::endl;

int main (void)
{
    std::vector<int> V1, V2;
    V1.push_back(-2);
    V1.push_back(0);
    V1.push_back(-1);
    V1.push_back(0);
    V1.push_back(1);
    V1.push_back(2);

    std::copy(V1.begin(), V1.end(), std::ostream_iterator<int>(cout, " "));
    cout << endl;

    std::remove_copy_if(
        V1.begin(),
        V1.end(),
        std::back_inserter(V2),
        std::bind2nd(std::less<int>(), 0));

    std::copy(V2.begin(), V2.end(), std::ostream_iterator<int>(cout, " "));
    cout << endl;
    std::copy(V1.begin(), V1.end(), std::ostream_iterator<int>(cout, " "));
    cout << endl;
}

It outputs:

-2 0 -1 0 1 2 
0 0 1 2 
-2 0 -1 0 1 2 

I was expecting so see something like:

-2 0 -1 0 1 2 
0 0 1 2 
0 0 1 2 ? ? ?

Where ? could be any value. But I was surprised to see that the input range was untouched, & that the return value is not able to be used with (in this case) std::vector::erase(). (The return value is an output iterator.)

5 Answers
Related