【问题标题】:Iterating over a set迭代一个集合
【发布时间】:2014-11-19 20:34:52
【问题描述】:

我正在尝试编写一些代码来覆盖给定集合的

template<typename T>
ostream& operator<<(ostream& out, const set<T> & v){    
    iterator myIt = v.begin();
    out << "{";
    while(myIt != v.end()-1) {
     out<<*myIt<<",";
     myIt++;
}
out << *myIt << "}";
return out;
}

然而这似乎不起作用,谁愿意给我一些建议?

【问题讨论】:

    标签: iterator set overloading operator-keyword ostream


    【解决方案1】:

    它甚至无法正确编译。另一个问题是,你假设你的集合不是空的。

    C++11 的设施有很大帮助:

    • 基于范围的 for 循环
    • 类型推演

    `

    template <typename T>
     ostream & operator<<(ostream& out, const set<T> & v) {
      string sep = "{";
      for (const auto &it : v) {
        out << sep << it << v;
        sep = ",";
      }
      return out << "}";
     }
    

    【讨论】:

      猜你喜欢
      • 2013-05-08
      • 2015-08-23
      • 2022-01-02
      • 2021-05-07
      • 1970-01-01
      • 2018-04-08
      • 2018-02-09
      • 2017-04-21
      相关资源
      最近更新 更多