Writing a map to a file

closed account (oEwqX9L8)
I have a map<string, vector<double>>. But I'm having some trouble accessing it (to write it to a file for example).

This is my loop to print the map. The problem is with "it->second," the vector.
1
2
3
  for (map<string, vector<double>>::iterator it=convertedGrades.begin(); it != convertedGrades.end(); ++it) {
        output << it->first << "\t" << it->second << endl;
    }


I'm thinking I need some way to loop through each index in the vector but I can't seem to figure how to do in this context. Thanks for any help!
Last edited on
Maybe you could rewrite the above code very slightly, split the output into three stages,

1
2
3
4
5
6
7
    for (map<string, vector<double>>::iterator it=convertedGrades.begin(); it != convertedGrades.end(); ++it) {
        output << it->first << "\t";

        // here add another loop to output each element of the vector<double>  it->second 
        
        output << endl;
    }

You could overload the << operator to output the vector.
1
2
3
4
5
6
7
8
ostream& operator<<(ostream& os, vector<double> &v)
{
  for (double d : v)
  {
    os << fixed << d << ' '; // add some formatting
  }
  return os;
}
It is an interesting design decision to implement your list of students as a mapping between name and list of grades. That was pretty cool, methinks. However, it does cause you an interesting set of difficulties, exacerbated by the fact that you did not explicitly specify types for your objects, increasing maintenance issues.

Nevertheless, you can output your students and their grades with a simple nested list:

1
2
3
4
5
6
7
8
for (auto student : convertedGrades)
  output << student.first;  // student.name

  for (auto grade : student.second)  // for each grade in student.grades
    output << "\t" << grade;

  output << "\n";
}

Hope this helps.
closed account (oEwqX9L8)
Thanks everyone for your help. Now I have a couple ways to approach it
Last edited on
Topic archived. No new replies allowed.