2

关于这个问题StackoVerflow 529831,这是建议的方法之一

template<typename Map> typename Map::const_iterator 
greatest_less(Map const& m, typename Map::key_type const& k) {
    //How to print K and Map m
    typename Map::const_iterator it = m.lower_bound(k);
    if(it != m.begin()) {
      return --it;
    }
    return m.end();
}

我会对打印键 K 和 Map m 感兴趣,该怎么做。

4

1 回答 1

4

使用<<运算符,确保为您的类型和类型<<都定义了它(您将知道是否不是这种情况,因为代码不会编译。)Map::key_typeMap::data_type

cout << k << endl;
for (typename Map::const_iterator it = m.begin(); it != m.end(); ++i) {
  cout << it->first << " -> " << it->second << endl;
}

例如,如果你Map::data_type是一个struct fraction与成员float numeratorfloat denominator

ostream& operator<<(ostream& os, const fraction& obj) {
   return os << obj.numerator << '/' << obj.denominator;
}
于 2009-03-14T18:08:08.600 回答