作为家庭作业的一部分,我们应该映射地图中每个角色的出现.我们的函数应该使用std :: for_each并传入要计算的字符.
我的功能是:
std::for_each(document_.begin(),
document_.end(),
std::mem_fun(&CharStatistics::fillMap));
Run Code Online (Sandbox Code Playgroud)
document_是一个string,并且fillMap函数定义为
void CharStatistics::fillMap(char ch)
{
ch = tolower(ch);
++chars_.find(ch)->second;
}
Run Code Online (Sandbox Code Playgroud)
chars_被宣布为std::map<char, unsigned int> chars_;.
我认为这应该有效,但编译器抱怨
error C2064: term does not evaluate to a function taking 1 arguments
Run Code Online (Sandbox Code Playgroud)
这让我感到困惑,因为当我查看参数列表时
_Fn1=std::mem_fun1_t<void,CharStatistics,char>,
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Alloc=std::allocator<char>,
1> _Result=void,
1> _Ty=CharStatistics,
1> _Arg=char,
1> _InIt=std::_String_iterator<char,std::char_traits<char>,std::allocator<char>>
Run Code Online (Sandbox Code Playgroud)
它对我来说很好看._Elem是一个char,我的函数接受一个char.迭代器只不过是一个char *
我究竟做错了什么?
CharStatistics::fillMap不是一个带有1个参数的函数.它是成员函数,所以它有隐含的第一个参数 - 指向类实例的指针.
在代码中:
std::for_each(document_.begin(),
document_.end(),
std::mem_fun(&CharStatistics::fillMap));
Run Code Online (Sandbox Code Playgroud)
for_each不知道你想打电话到哪个实例CharStatistics::fillMap,你没有指定它.您需要将它与任何CharStatistics实例绑定,例如:
std::bind1st(std::mem_fun(&CharStatistics::fillMap), &char_statistics_instance)
Run Code Online (Sandbox Code Playgroud)