ReadingLab/Discussion-for-Cpp

练习题11.4 找不到remove_if函数

EnzoFerrari430 opened this issue · 2 comments

我运行就报错说未找到remove_if函数,换成find_if也不行
我的环境是codeblocks(GNU GCC COMPILER 勾选了C++11) + win7 32位下面是代码

#include <iostream>
#include <map>
#include <string>
#include <cctype>
#include <algorithm>
#include <numeric>
using namespace std;
//ispunct  是特殊字符返回非0  否则返回0
string to_be_low(string &s)
{
    for( auto &c : s)
    {
        c = tolower(c);
    }
    //s.erase(remove_if(s.begin(),s.end(),ispunct),s.end());
    s.erase(find_if(s.begin(),s.end(),ispunct));
    return s;
}
int main()
{
    map<string,size_t> word_count;
    string word;
    while(cin>>word)
    {
        to_be_low(word);
        ++word_count[word];
    }
    //打印结果
    for(const auto &w:word_count)
    {
        cout<<w.first<<": occurs: "<<w.second<<( w.second > 1? " times" : " time" )<<endl;
    }
    return 0;
}
pezy commented

这不是 remove_iffind_if 的锅。

是因为 ispunct 在编译器实现里有别的重载版本,所以导致编译器不知道你指的是哪一个。

显然在这里,你用的是 C 语言库里那个,那么你应该指定一下:::ispunct.


或者,你非要使用 std 版本那个,那么一定要指定好参数类型(unsigned char):

s.erase(remove_if(s.begin(),s.end(),[](unsigned char c){
    return std::ispunct(c);
}),s.end());

原因请见 Note:
image

哦,原来是这样。多谢多谢