【发布时间】:2021-09-16 19:59:19
【问题描述】:
我想计算 const string& 中的字母,并将结果保存在 map 中。
但是编译器抛出错误:
错误:要求从“const char”转换为非标量类型“std::string”{又名“std::__cxx11::basic_string”}
我的代码:
map<string, int>& MakeWordCounter (const string& word, map<string, int>& cnt) {
for (string i : word) {
cnt[i] = count(word.begin(), word.end(), i);
}
}
怎么做?
【问题讨论】:
-
循环
for (string i : word)遍历字符串word中的字符。变量i必须是char。 -
是否要拆分输入字符串?您的输入和预期输出是什么?
-
我的输入是:"foobar_aaa",预期输出是 map {{"f", 1}, {"o", 2}, {"b", 1}, {"a", 4}, {"r", 1}, {"_", 1}}
-
for (char i : word) {或for (auto i : word) {。 -
还有一个问题是函数被声明返回一些东西,但实际上没有返回任何东西。
标签: c++ dictionary stl