Reputation: 861
I am not sure how to access the map inside the struct Student Some examples that I look up says -> first ->second but this does not compile.
How I can access map inside the struct? or the overloading of the operator is wrong?
the error says ‘->’ 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;
}
Upvotes: 0
Views: 253
Reputation: 115
I haven't understood the problem. It's more elaborate if you show us the sample output. sorry if I am wrong, I am unable to find when you are going to stop reading data. . ?
You need to use pair to insert to map and to traverse you should use iterator. Hope this helps:
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;
}
Upvotes: 0
Reputation: 1545
The main difference between .
and ->
is the type of objet you have at the beginning. Use .
when you have your object, and ->
when you have a pointer to your object
If you define a Student this way
Student erik = ...
You'll get erik's id like this :
erik.id
If you define erik like this :
Student* erik = ...
you'll get his id like this :
erik->id
And that's what the error mean
But you have another problem, since first
and second
are not defined for a map, but for a map element. You'll need to iterate through the map in order to do what you want. I'd guess something like this would be better
os << g.id << '\n'
for (auto& it : g.scores) {
os<< it.first << it.second << '\n' ;
}
Upvotes: 1