c++c++11stl-algorithm

remove_copy usage with strings


My string is !!(!()). I want to remove double exclamation from the string.

This works but it removes all exclamations

remove_copy(str.begin(), str.end(),ostream_iterator<char>(cout), '!');//gives (())

This does not work

remove_copy(str.begin(), str.end(),ostream_iterator<string>(cout), "!!");

Using the above line throws this error

/usr/include/c++/5/bits/predefined_ops.h:194:17: error: ISO C++ forbids comparison between pointer and integer [-fpermissive] { return *__it == _M_value; }


Solution

  • Reading the docs of remove_copy

    OutputIterator remove_copy (InputIterator first, InputIterator last,
                              OutputIterator result, const T& val);
    
    The function uses operator== to compare the individual elements to val.
    

    So it uses every character of string and compares it with val. So second case would not work.

    I ended up doing it this way

    str.erase(str.find("!!"),2);
    

    Also make sure that the string has "!!" otherwise program crashes

    if(str.find("!!") != string::npos)
        str.erase(str.find("!!"),2);