我想计算常量字符串中的字母数&,并将结果保存在地图中
但编译器抛出错误:
错误:从"const char"转换为非标量类型"std::string"{aka"std:"__cxx11::basic_string"}请求
我的代码:
map<string, int>& MakeWordCounter (const string& word, map<string, int>& counter) {
for (string i : word) {
counter[i] = count(word.begin(), word.end(), i);
}
}
为什么会发生此错误,以及如何修复?
word
的去引用迭代器的类型为char
,我们无法将其转换为字符串。并且函数声明可以更清楚地直接返回映射。
这里的键类型是char,我们不需要使用string
类型,它具有误导性,是一种浪费。
std::map<char, size_t> MakeWordCounter(const std::string& word) {
std::map<char, size_t> counts;
for (auto ch : word) {
counts[ch]++;
}
return counts;
}
或者我们可以使用STL算法而不是循环:
std::map<char, size_t> MakeWordCounter2(const std::string& word) {
return std::accumulate(word.begin(), word.end(), std::map<char, size_t>{},
[](auto init, char cur) {
init[cur] += 1;
return init;
});
}
你可能会怀疑第二个版本的性能,所以我在这里添加了基准,这两个版本通常是相同的。
https://quick-bench.com/q/OSzzp70rBSdlpivEMmMIj0aGJfU
在线演示