C++使用find_if报错:expression cannot be used as a function 问题求助
问题分析与修复
错误原因
你代码里的find_if调用存在参数使用错误:
find_if(sCount.begin(), sCount.end(), lp)
find_if的第三个参数要求是可调用的谓词(判断逻辑),但你直接传入了char类型的lp。编译器会尝试把lp当作函数执行(对应报错里的_M_pred(*__it)),而字符无法作为函数使用,因此触发了"expression cannot be used as a function"错误。
另外你的统计逻辑还有疏漏:新插入字符时设置值为0,会导致最终统计结果比实际出现次数少1(比如测试用例"aba"里的'a'会被统计成1,而非正确的2)。
修复方案(两种可选)
方案1:简化写法(推荐)
利用std::map的operator[]特性:当访问的键不存在时,会自动插入该键并将值初始化为0。统计逻辑可以直接简化,完全不需要find_if:
using namespace std; map<char, int> count_chars(const string& s) { map<char, int> sCount {}; for (char c : s) { sCount[c]++; // 不存在的键自动初始化为0,随后加1 } return sCount; } int main() { string test = "aba"; map<char, int> res = count_chars(test); for (auto& pair : res) { cout << pair.first << ":" << pair.second << endl; } return 0; }
运行后会正确输出:
a:2 b:1
方案2:修正find_if的用法
如果一定要用find_if判断键是否存在,需要传入lambda表达式作为谓词,用来比较map元素的键和目标字符:
using namespace std; map<char, int> count_chars(const string& s) { map<char, int> sCount {}; for (char c : s) { // 用lambda判断当前map元素的键是否等于目标字符c auto it = find_if(sCount.begin(), sCount.end(), [c](const pair<char, int>& elem) { return elem.first == c; }); if (it != sCount.end()) { it->second += 1; } else { sCount.insert(make_pair(c, 1)); // 新字符直接初始化为1 } } return sCount; } int main() { string test = "aba"; map<char, int> res = count_chars(test); for (auto& pair : res) { cout << pair.first << ":" << pair.second << endl; } return 0; }
内容的提问来源于stack exchange,提问作者lakvak
相关产品推荐
相关产品推荐

