示例:
#include<iostream>
using namespace std;
#include<map>
class Mycompare
{
public:
bool operator()(int v1, int v2)const
{
return v1 > v2;
}
};
void printMap(map<int, int, Mycompare>& m)
{
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "first = " << (*it).first << " second = " << it->second << endl;
}
cout << endl;
}
void test01()
{
map<int, int, Mycompare>m1;
m1.insert(make_pair(1, 30));
m1.insert(make_pair(5, 20));
m1.insert(make_pair(4, 40));
m1.insert(make_pair(2, 50));
m1.insert(make_pair(3, 10));
printMap(m1);
}
int main()
{
test01();
return 0;
}
总结:
1.利用仿函数可指定map排序规则;
2.插入自定义数据类型时,map要指定排序规则,否则编译器不知道怎么排