1.目的:map容器默认按照key从小到大的升序排列,学习如何改变排序规则
2.解决方案:利用仿函数可以改变排序规则,即实现降序排列
#include<iostream>
#include<map>
using namespace std;
class mycompare
{
public:
bool operator()(int a, int b) const
{
return a > b;
}
};
void printmap(map<int, int,mycompare>& m)
{
for (map<int, int,mycompare>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key=" << it->first << " value=" << (*it).second << endl;
}
cout << endl;
}
void test1()
{
map<int, int,mycompare> m;
//插入
//第一种
m.insert(pair<int, int>(1, 10));
//第二种,优先推荐
m.insert(make_pair(2, 20));
//第三种
m.insert(map<int, int>::value_type(3, 30));
//第四种,[]方式不建议用于插入,但可以用于按照key来访问对应的value
m[4] = 40;
printmap(m);
/*
key=4 value=40
key=3 value=30
key=2 value=20
key=1 value=10
*/
}
int main()
{
test1();
return 0;
}