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

no operator '>>' matches these operands

本文关键字:gt 操作数 运算符      更新时间:2023-10-16

我的程序不会编译,因为它找不到与操作数匹配的内容。它访问结构Student中的映射,我不确定这是否是访问映射的确切方式。

我的程序无法编译,因为它找不到与操作数匹配的内容。它访问结构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;
}

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

Error: no operator ">>" matches these operands
    operand types are: std::basic_istream<char, std::char_traits<char>> >> const std::string

您可以使用临时变量

std::string tempStr;
int tempInt;
is >> g.id >> tempStr >> tempInt;
scores.insert( std::pair<std::string,int>(tempStr , tempInt));

错误是由于it->first的类型是const string,而不是string

除此之外,您还需要找到一种方法,通过读取(未知)数量的字符串和相应的int来读取映射。如何做到这一点取决于它们在文件中的存储方式。