将map <string int>写入文件 - 不匹配'operator <<'

Lin*_*nda 0 c++

当我编译我的C++项目时,我得到一个我不明白的错误.我的错误在以下代码部分中引发:

void twogramsToFile(const map <string,int> twogram, const string outputfile) {
  ofstream myfile (outputfile);

  for (auto &x : twogram) {
    outputfile << x.first << " " << x.second << "\n"; //this line causes the error
  }

  myfile.close();
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误信息是这个:

no match for ‘operator<<’ (operand types are ‘const string {aka const std::__cxx11::basic_string<char>}’ and ‘const std::__cxx11::basic_string<char>’)
Run Code Online (Sandbox Code Playgroud)

我认为<<运算符是为内置类型定义的.

Use*_*ess 5

我认为<<运算符是为内置类型定义的.

这不是它抱怨的右手边,而是左手边.您可以 const字符串流式传输,但不能流式传输 const字符串.尝试

myfile << ...
Run Code Online (Sandbox Code Playgroud)

  • 如果你仔细阅读错误信息,它实际上*说*`operator <<的参数是*都是*`std :: string`. (2认同)