如何使用remove_if!一个函数(不是一个函数)

use*_*963 2 c++ string algorithm

基本上,我试图这样做:

word.resize(remove_if(word.begin(),word.end(),not1(isalpha())) - word.begin());

我知道丑陋的解决方法,你只需要声明自己的功能并传递它.但有没有办法让这个工作?我在isalpha函数下面有一条红线,显示"函数调用中的参数太少"的消息.

Jer*_*fin 6

在C++ 03中,您通常使用以下内容:

std::not1(std::ptr_fun(isalpha))
Run Code Online (Sandbox Code Playgroud)

在C++ 11中,您经常使用lambda:

word.resize(
   remove_if(word.begin(), word.end(), 
             [](char ch){return !isalpha(ch);}) -word.begin());
Run Code Online (Sandbox Code Playgroud)

编辑:您可能还想阅读昨天在Code Review上提出的类似问题.它不完全相同,但足够相似以至于它可能是有趣的(它不是要求!isalpha,而是从字符串中删除非字母字符).

Edit2:做一个快速测试,这似乎工作:

#include <algorithm>
#include <string>
#include <iostream>
#include <iterator>
#include <ctype.h>

template <class T>
T gen_random(size_t len) {
    T x;
    x.reserve(len);

    std::generate_n(std::back_inserter(x), len, rand);
    return x;
}

template <class Container>
void test2(Container &input) {
    input.resize(
        std::remove_if(input.begin(), input.end(), 
        [](char ch){return !isalpha(ch);}) -input.begin());
}

int main(){

    std::string input(gen_random<std::string>(100));
    std::cout << "Input: \n" << input << "\n\n";

    input.resize(
        std::remove_if(input.begin(), input.end(), 
        [](char ch){return !isalpha(ch);}) -input.begin());

    std::cout << "Result: " << input << "\n";

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

至少在我运行时,我得到:

Input:
ë??G???M?C?ïª??Z}       8%?]???û?E;?
??«2 ÜP?@x6²?I2÷?}I?¡O¶?D@f?k?0?2;í"÷"æ¥

Result: lRIGMCZEPxIIODfk
Run Code Online (Sandbox Code Playgroud)

根据事物的外观,我生成的随机输入包括至少一个回车符,因此输入中的前几个字符在输出中不可见.我从"G"开始检查了一对,然后在最后检查了一对,但看起来一切都很顺利.