Auclair
Auclair

Reputation: 125

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

I have a class for a course catalog with a private variable of type map<string, string> Courses. I want to overload << as a friend operator so that when I output for instance Courses["TMA4100"] it will output both "TMA4100" and the name of the course, not only the name. The reason is so that I can store the catalog in a file instead of having the catalog be erased when I shut down the program.

I'm not very familiar with maps, so I don't really know how to overload the operator to handle maps. This was my initial attempt:

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

Now that I've thought about it, this doesn't make much sense at all because I won't be passing a string into the operator, but rather the map with a key. Can anybody point me in the right direction?

Upvotes: 0

Views: 57

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

To store the entire catalog, overload the operator for your own class, not for the map or a string.

Example:

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

A suggestion about entry-wise access:

For added flexibility, create a class that holds course information and store those instead of strings:

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

Your catalog will now be a std::map<string, CourseInfo>, and you can overload << for CourseInfo:

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

and you can write (using a fictitious interface for your class):

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

Upvotes: 4

Related Questions