[英]error: conversion from ‘const char’ to non-scalar type ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} requested
I want to count letters in const string&, and save result in map.我想计算 const string& 中的字母,并将结果保存在地图中。
But compiler throws an error:但是编译器会抛出一个错误:
error: conversion from 'const char' to non-scalar type 'std::string' {aka 'std::__cxx11::basic_string'} requested
错误:请求从 'const char' 转换为非标量类型 'std::string' {aka 'std::__cxx11::basic_string'}
My code:我的代码:
map<string, int>& MakeWordCounter (const string& word, map<string, int>& counter) {
for (string i : word) {
counter[i] = count(word.begin(), word.end(), i);
}
}
Why this error is happening and how to fix it?为什么会发生此错误以及如何解决?
The dereferenced iterator of word
has the type char
, we can't convert it to string. word
的解引用迭代器具有char
类型,我们不能将其转换为字符串。 And the function declaration can be more clear to directly return the map.并且函数声明可以更清晰直接返回map。
The key type here is char, we don't need to use a string
type, its misleading and is a waste.这里的关键类型是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;
}
Or we can use STL algorithm instead of loop:或者我们可以使用 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;
});
}
You may doubt the second version's performance, so I add the benchmark here, the two versions are generally the same.你可能会怀疑第二个版本的性能,所以我在这里添加基准,两个版本大致相同。
https://quick-bench.com/q/OSzzp70rBSdlpivEMmMIj0aGJfU https://quick-bench.com/q/OSzzp70rBSdlpivEMmMIj0aGJfU
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.