【问题标题】:C++: Printing out map valuesC++:打印出地图值
【发布时间】:2013-11-14 11:25:46
【问题描述】:

所以我有一张这样的地图:

map<long, MusicEntry> Music_Map;

MusicEntry 包含(名称、艺术家、大小和添加日期)的字符串

我的问题是如何打印,如何打印出地图中的所有数据?我试过做...

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

我认为问题在于它无法编译和读取第二个又名 MusicEntry..

【问题讨论】:

    标签: c++ for-loop printing map


    【解决方案1】:

    你需要提供一个std::ostream operator&lt;&lt; (std::ostream&amp;, const MusicEntyr&amp;),这样你才能做这种事情:

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

    有了它,您可以打印地图的second 字段。这是一个简化的示例:

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

    【讨论】:

      【解决方案2】:

      你的代码很好,但你需要实现

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

      您可能需要在MusicEntry 中声明上述friend 才能访问MusicEntry 的私有(或受保护)数据:

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

      当然,如果数据是公开的或者您使用公共 getter,则不需要这样做。您可以在operator overloading FAQ 中找到更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-05
        • 2017-06-09
        • 2020-01-11
        • 2015-12-24
        相关资源
        最近更新 更多