没有运算符'>>'匹配这些操作数

XDP*_*mer -2 c++ operator-overloading

我的程序不会编译,因为它没有找到操作数匹配.它访问struct Student中的地图,我不确定这是否是访问地图的确切方法.

我的程序不会编译,因为它没有找到操作数匹配.它访问struct Student中的地图,我不确定这是否是访问地图的确切方法.

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <string>
#include <map>
#include <list>


using namespace std;

struct Student {
    string id;
    map<string, int> scores;
};

istream& operator >>(istream &is, Sudent& g) {

    auto it = g.scores.begin();
    is >> g.id >> it->first >> it.second;
    return is;
}
Run Code Online (Sandbox Code Playgroud)

>> it->first我得到这个错误:

Error: no operator ">>" matches these operands
    operand types are: std::basic_istream<char, std::char_traits<char>> >> const std::string
Run Code Online (Sandbox Code Playgroud)

Ste*_*hen 6

您可以使用临时变量

std::string tempStr;
int tempInt;
is >> g.id >> tempStr >> tempInt;
scores.insert( std::pair<std::string,int>(tempStr , tempInt));
Run Code Online (Sandbox Code Playgroud)

  • 正确的解决方案,但需要解释为什么OP做错了.没有解释的解决方案导致货物崇拜行为. (2认同)