重载 << 以输出地图的 key_type 和 mapped_type

Overloading << to output both key_type and mapped_type for a map

我有一个 class 课程目录,其中包含 map<string, string> Courses 类型的私有变量。我想重载 << 作为友元运算符,这样当我输出例如 Courses["TMA4100"] 时,它会同时输出 "TMA4100" 和课程名称,而不仅仅是名称。原因是我可以将目录保存在一个文件中,而不是在关闭程序时让目录被删除。

我对地图不是很熟悉,所以我真的不知道如何重载运算符来处理地图。这是我最初的尝试:

std::ostream &operator << (std::ostream &outStream, const string coursecode){
outStream << coursecode << " " << Courses[coursecode];}

现在我已经考虑过了,这根本没有多大意义,因为我不会将字符串传递给运算符,而是传递带有键的映射。谁能指出我正确的方向?

要存储整个目录,请为您自己的 class 重载运算符,而不是为地图或字符串重载。

示例:

std::ostream& operator<<(std::ostream& os, const YourClass& catalog)
{
    for (const auto& entry: catalog.Courses)
    {
        os << entry.first << " " << entry.second << '\n';
    }
    return os;
}

关于入口访问的建议:

为了增加灵活性,创建一个 class 来保存课程信息并存储这些信息而不是字符串:

struct CourseInfo
{
    std::string name;
    std::string description;
    StaffMember teacher;
    // ... more useful stuff ...
};

您的目录现在将是 std::map<string, CourseInfo>,您可以为 CourseInfo 重载 <<:

std::ostream& operator<<(std::ostream& os, const CourseInfo& info)
{
    os << info.name << " " << info.description << " " << info.teacher;
    return os;
}

你可以写(为你的 class 使用一个虚构的界面):

YourClass catalog;
// ... populate the catalog
std::cout << catalog.courseInfo("TM4100") << std::endl;