kal
kal

Reputation: 29353

How do perform a generic print for key type and map

With reference to this question StackoVerflow 529831, this was one of the suggested approaches

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();
}

I would be interested in printing key K and Map m, How would go about this.

Upvotes: 2

Views: 767

Answers (1)

vladr
vladr

Reputation: 66661

Use the << operator, making sure that << is defined for both your Map::key_type and Map::data_type types (you will know if that is not the case as the code will not compile.)

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

e.g. if your Map::data_type is a struct fraction with members float numerator and float denominator,

ostream& operator<<(ostream& os, const fraction& obj) {
   return os << obj.numerator << '/' << obj.denominator;
}

Upvotes: 4

Related Questions