error: conversion from ‘const char’ to non-scalar type ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} requested

error: conversion from ‘const char’ to non-scalar type ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} requested

我想计算 const string& 中的字母,并将结果保存在 map 中。
但是编译器抛出错误:

error: conversion from ‘const char’ to non-scalar type ‘std::string’ {aka ‘std::__cxx11::basic_string’} requested

我的代码:

map<string, int>& MakeWordCounter (const string& word, map<string, int>& cnt) {
    for (string i : word) {
        cnt[i] = count(word.begin(), word.end(), i);
    }
}

怎么做?

word 的取消引用迭代器的类型为 char,我们无法将其转换为字符串。并且函数声明直接return映射可以更清晰

这里的键类型是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

Online demo