Vad Sim
Vad Sim

Reputation: 316

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.
But compiler throws an error:

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

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?

Upvotes: 1

Views: 8203

Answers (1)

prehistoricpenguin
prehistoricpenguin

Reputation: 6326

The dereferenced iterator of word has the type char, we can't convert it to string. And the function declaration can be more clear to directly return the map.

The key type here is char, we don't need to use a string type, its misleading and is a waste.

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:

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

Online demo

Upvotes: 3

Related Questions