Tyler
Tyler

Reputation: 2063

C++: Printing out map values

So I have a map like this:

map<long, MusicEntry> Music_Map;

MusicEntry contains strings of (name, artist, size, and date added)

My question is how can print, how do I print out all the data in my map? I have tried doing...

   for(auto it = Music_Map.cbegin(); it!= Music_Map.cend(); ++it)
    cout << it-> first << ", " <<  it-> second << "\n";

I think the problem is occuring that it can't compile and read second aka MusicEntry..

Upvotes: 0

Views: 908

Answers (2)

Daniel Frey
Daniel Frey

Reputation: 56863

The code you have is fine, but you need to implement

std::ostream& operator<<(ostream& os, const MusicEntry& e)
{
    return os << "(" << e.name << ", " << ... << ")";
}

and you probably need to declare the above a friend in MusicEntry to access the private (or protected) data of MusicEntry:

class MusicEntry
{
    // ...

    friend std::ostream& operator<<(ostream& os, const MusicEntry& e);
};

This is, of course, not needed if the data is public or if you use public getters. You can find a lot more information in the operator overloading FAQ.

Upvotes: 2

juanchopanza
juanchopanza

Reputation: 227418

You need to provide an std::ostream operator<< (std::ostream&, const MusicEntyr&) so that you can do this kind of thing:

MusicEntry m;
std::cout << m << std::endl;

With that in place, you can print the map's second fields. Here's a simplified example:

struct MusicEntry
{
  std::string artist;
  std::string name;
};

std::ostream& operator<<(std::ostream& o, const MusicEntry& m)
{
  return o << m.artist << ", " << m.name;
}

Upvotes: 2

Related Questions