使用map的结构体的ostream运算符重载

3
我已经为学生创建了一个成绩结构体,并尝试重载'<<'运算符。
// 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,另一个用于string:grades.id?

感谢您的帮助。


这个问题相当不清楚。将您展示的地图输出放入“Grades”的<<运算符中,基本上会给您想要的结果。 >>不应该产生输出。您到底在问什么? - Angew is no longer proud of SO
@Angew 那是我的错,让我试着编辑一下。 - andres
2个回答

3

看起来很奇怪,你竟然不能自己解决这个问题。如果我正确理解了问题,你只需要将这两个重载合并成一个,这样你就可以像这样迭代const Grades gmap

#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;
}

1

对于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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接