永发信息网

c++ map 容器排序

答案:2  悬赏:0  手机版
解决时间 2021-04-02 09:44
  • 提问者网友:不爱我么
  • 2021-04-02 03:21
c++ map 容器排序
最佳答案
  • 五星知识达人网友:神也偏爱
  • 2021-04-02 04:18
默认遍历序是根据key升序排列的。
map m;
for (map::iterator it = m.begin(); it != m.end(); ++it)
{
// it->first 是 key, it->second 是 value,遍历顺序是按key升序。
cout << it->first << ":" << it->second << endl;
}
全部回答
  • 1楼网友:舍身薄凉客
  • 2021-04-02 05:16
很简单:
#include <map>
#include <string>
#include <functional>
std::map<std::string,std::string,std::greater<std::string> > container;
因为map的定义默认是用std::less来比较的,而std::less和std::greater都在同一个头文件<functional>里面,可能map本身就包含着<functional>,你试一试你的库实现里面能不能把#include<functional>删去但仍然能用std::greater模板。std::less和std::greater本身也很简单。如果你不想包含着一个这样的文件(因为functional里面还有很多的函数对象),可以自己写:
template<class T> struct greater{
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
// 一般来说上面三句可有可无,因为没有什么用。下面这句才是根本。
bool operator()(const T& a,const T& b) { return a > b; }
};
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯