我不确定如何访问 Student 结构中的 map 我查找的一些例子说 -> 第一 -> 第二 但这不会编译。
我如何访问结构内部的 map ? 或者运算符的重载是错误的?
错误提示‘->’有非指针类型
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 :
学生* erik = ...
你会像这样得到他的 id :
erik->id
这就是错误的意思
但是您还有另一个问题,因为 first
和 second
不是为 map 定义的,而是为 map 元素 定义的。您需要遍历 map 才能执行您想要的操作。我想这样的事情会更好
os << g.id << '\n'
for (auto& it : g.scores) {
os<< it.first << it.second << '\n' ;
}
关于c++ - 如何访问 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31044818/