2

基本上,我正在尝试这样做:

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

我知道你只需声明自己的函数并传递它的丑陋解决方法。但是有没有办法让这个工作?我收到消息“函数调用中的参数太少”,isalpha 函数下方有一条红线。

4

1 回答 1

6

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

std::not1(std::ptr_fun(isalpha))

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

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

编辑:您可能还想阅读昨天在 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;
}

至少当我运行它时,我得到:

Input:
ë♠╖G▐│↕M╚C╗ïª▼♥Z}       8%▼]╘╦ⁿû⌡E;‼
∟█«2 ÜPε@x6²↕I2÷₧}I▄¡O¶≥D@f╨k─0╖2;í"÷"æ¥

Result: lRIGMCZEPxIIODfk

从外观上看,我生成的随机输入至少包含一个回车,因此输入中的前几个字符在输出中不可见。我检查了从“G”开始的一对,然后检查了最后一对,但一切似乎都很好。

于 2012-04-27T19:13:38.820 回答