在stl中自定义map比较函数有两种方式,方式一在类中重载<操作符,方式二仿比较函数
1、方式一:重载<操作符
#include "stdafx.h"
#include <map>
#include <string>
#include <iostream>
using namespace std;
class Key
{
public:
Key(string name, int age)
{
this->name=name;
this->age=age;
}
~Key(){}
string getName()
{
return name;
}
int getAge()
{
return age;
}
bool operator<(const Key& key) const
{
if(age!=key.age)
{
return age<key.age;
}
else
{
return false;
}
}
private:
string name;
int age;
};
int main(void)
{
Key key1("cjc",25);
Key key2("ldb",26);
Key key3("jzm",27);
map<Key,string> s;
s[key1]="He is a boy.";
s[key2]="He is a student.";
s[key3]="He is a old man.";
map<Key,string>::iterator it=s.begin();
while(it!=s.end())
{
cout&l