gpt4 book ai didi

c++ - 如何为键类型和映射执行通用打印

转载 作者:搜寻专家 更新时间:2023-10-31 01:23:50 24 4
gpt4 key购买 nike

引用这个问题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 很感兴趣,这将如何进行。

最佳答案

使用 <<运算符(operator),确保 <<为您的 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_typestruct fraction与成员(member)float numeratorfloat denominator ,

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

关于c++ - 如何为键类型和映射执行通用打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/646392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com