我不明白如何在 c++ 中做一个remove_if

I don't understand how to do a remove_if not in c++

本文关键字:一个 remove if 明白 c++      更新时间:2023-10-16

这段代码有效,但有点有限,所以如果它不等于一个字母,我想删除一些东西。

我知道我必须使用:isalpha而不是:ispunct,但我不知道如果它不等于::isalpha。我仔细研究了这个问题,但没有得到任何答案,因为我不明白。

textFile[i].erase(remove_if(textFile[i].begin(), textFile[i].end(), ::ispunct), textFile[i].end());

感谢您的帮助。

我还没有编译,但这应该可以工作:

textFile[i].erase(
    remove_if(textFile[i].begin(), textFile[i].end(), std::not1(std::ptr_fun(::isalpha))),
    textFile[i].end());

这里感兴趣的链接是:

  • http://www.cplusplus.com/reference/std/functional/ptr_fun/
  • http://www.cplusplus.com/reference/std/functional/not1/

如果标准函子还不够,您还可以实现自己的:

struct not_a_character : std::unary_function<char, bool> {
    bool operator()(char c) const {
        return !isalpha(c);
    }
};

可以用作:

textFile[i].erase(
    remove_if(textFile[i].begin(), textFile[i].end(), not_a_character()),
    textFile[i].end());