引用这个问题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();
}
我有兴趣打印 key K 和 map m,如何解决这个问题。
最佳答案
使用<<
运算符,确保 <<
为您的 Map::key_type
定义和Map::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
与成员(member) float numerator
和float denominator
,
ostream& operator<<(ostream& os, const fraction& obj) {
return os << obj.numerator << '/' << obj.denominator;
}
关于c++ - 如何执行键类型和映射的通用打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/646392/