带有映射的结构的 ostream 运算符重载

ostream operator overload for struct with map

我已经为学生创建了一个成绩结构,并试图重载“<<”运算符。

// Sample output:
a12345678
2             //number of elements in map
COMP3512 87  
COMP3760 68

struct Grades {
  string             id;       // student ID, e.g,, a12345678
  map<string, int> scores;     // course, score, e.g. COMP3512, 86
};

我之前重载过operator<<独立获取信息

ostream& operator<<(ostream& os, const Grades g) { 
  return os << g.id << '\n' ... 

  // return os << g.id << '\n' << g.scores;   produces an error
}

我怀疑这与地图的重载没有正确的语法有关,如下所示。

ostream& operator<<(ostream& os, const map<string, int>& s) {
  for (auto it = s.begin(); it != s.end(); ++it) 
    os << (*it).first << ' ' << (*it).second << endl;

  return os;
}

有没有一种方法可以通过一个重载生成示例输出,或者我是否需要两种当前实现:一种用于 map:grades.scores,另一种用于字符串:grades.id

感谢您的协助。

没有为std::map提供标准<<,只能自己输出了。但是没有什么能阻止您将您的实现合并到一个函数中:

std::ostream& operator<< (std::ostream &os, const Grades &g)
{
  os << g.id << '\n';
  os << g.scores.size() << '\n';
  for (const auto &s : g.scores) {
    os << s.first << ' ' << s.second << '\n';
  }
  return os;
}

你不能自己解决这个问题似乎很奇怪,因为如果我正确理解了这个问题,你只需要将两个重载合并为一个,这样你就可以从 [= 迭代 map 12=] 像这样:

#include <iostream>
#include <map>
#include <string>

using namespace std;

struct Grades {
    string             id;       // student ID, e.g,, a12345678
    map<string, int> scores;     // course, score, e.g. COMP3512, 86
};


ostream& operator<<(ostream& os, const Grades g) { 
    os << g.id << endl << g.scores.size() << endl;
    for (auto it = g.scores.begin(); it != g.scores.end(); ++it) 
        os << (*it).first << ' ' << (*it).second << endl;
    return os;
}

int main(int argc, char** argv)
{
    Grades g;
    g.id = "a12345678";
    g.scores["COMP3512"] = 87;
    g.scores["COMP3760 "] = 68;
    cout << g;
    return 0;
}