remove_copy 字符串用法

remove_copy usage with strings

我的字符串是!!(!())。我想从字符串中删除双感叹号。

这有效,但它删除了所有感叹号

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

这行不通

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

使用上面的行会抛出这个错误

/usr/include/c++/5/bits/predefined_ops.h:194:17: 错误:ISO C++ 禁止比较指针和整数 [-fpermissive] { return *__it == _M_value; }

正在阅读 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.

因此它使用字符串的每个字符并将其与 val 进行比较。所以第二种情况是行不通的。

我最后是这样做的

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

还要确保字符串中有“!!”否则程序崩溃

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

为什么不能使用 remove_copy(str.begin(), str.end(),ostream_iterator<string>(cout), "!!"); :

https://www.cplusplus.com/reference/algorithm/remove_copy_if/

pred
Unary function that accepts an element in the range as argument, and returns a value convertible to bool. The value returned indicates whether the element is to be removed from the copy (if true, it is not copied). The function shall not modify its argument. This can either be a function pointer or a function object.