如何访问地图

How to access map?

本文关键字:地图 访问 何访问      更新时间:2023-10-16

我不知道如何访问结构Student内部的映射我查到的一些例子说->第一个->第二个但这不会编译。

如何访问结构中的映射?或者操作员过载是错误的?

错误显示‘->’ has non-pointer type

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

ostream& operator<<(ostream& os, const Student& g){
    return os << g.id << 'n' <<  g.scores->first << 'n' << g.scores->second ;
}
istream& operator >>(istream& is, Student& g){
    return is >> g.id >> g.scores->first >> g.scores->second;
}

int main() {
    vector<Student> g_vec;
    Student grades;
    while(cin >> gd)
        g_vec.push_back(grades);
    for (auto& g : g_vec)
        cout << g << endl;
    }

.->之间的主要区别在于开头的对象类型。当您有对象时使用.,当您有指向对象的指针时使用->

如果你这样定义学生

Student erik = ...

你会得到这样的erik的id:

erik.id

如果你这样定义erik:

Student* erik = ...

你会得到这样的身份证:

erik->id

这就是错误的意思

但您还有另一个问题,因为firstsecond不是为映射定义的,而是为映射元素定义的。您需要在映射中进行迭代,以便执行您想要的操作。我想像这样的东西会更好

os << g.id << 'n'
for (auto& it : g.scores) {
    os<< it.first << it.second << 'n' ;
}

我还没有理解这个问题。如果你给我们看一下样品输出,会更详细。对不起,如果我错了,我找不到你什么时候停止读取数据?

您需要使用pair来插入映射和遍历,您应该使用迭代器。希望这有帮助:

ostream& operator<<(ostream& os, const Student& g){
      //here you need to write for loop to traverse the entire map. I am printing only last ele. .  
    map<string,double>::const_iterator myit = g.scores.end();
    os << g.id << 'n' <<  myit->first << 'n' << myit->second ;
    return os;
}
istream& operator >>(istream& is, Student& g){
    pair<string,double> mypair;
    is >> g.id >> mypair.first >> mypair.second;
    g.scores.insert(mypair);
    return is;
}