remove_copy字符串的用法

remove_copy usage with strings

本文关键字:用法 字符串 copy remove      更新时间:2023-10-16

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

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

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++禁止指针和整数之间的比较 [-permissive] { 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
一元函数,它接受范围内的元素作为参数,并返回可转换为 bool 的值。返回的值指示是否要从副本中删除元素(如果为 true,则不是复制)。该函数不得修改其参数。这可以是函数指针或函数对象。