【问题标题】:error: conversion from ‘const char’ to non-scalar type ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} requested错误:请求从‘const char’转换为非标量类型‘std::string’ {aka ‘std::__cxx11::basic_string<char>’}
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-03
    • 2021-10-28
    • 1970-01-01
    • 2017-03-10
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多