0

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..

Tyler
  • 1,933
  • 5
  • 18
  • 23

2 Answers2

2

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;
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

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.

Community
  • 1
  • 1
Daniel Frey
  • 55,810
  • 13
  • 122
  • 180