一. 数据结构:
Map的数据结构是二叉树(红黑树),可以认为是平衡搜索二叉树,按照key值进行排序的。于是,key值的类型应该有比较操作。
int, string类型等可以进行默认的比较操作。
对于自定义的结构和类型,需要定义比较操作才能做key值。
二. 定义比较操作
1. 可以在类型中重载operator<操作:
bool operator<(const A& a)const{}
2. 定义一个类来实现operator()函数操作:
bool operator()(const A& a, const A& b)const{}
也是实现重载;
3. 定义一个比较函数,在声明map<>的时候用函数指针调用它。
bool funcPComp(const A& a, const A& b){}
代码如下:
#include <iostream>
#include <map>
using namespace std;
static int num = 0;
class A{
public:
A(){i = num++;}
bool operator<(const A&a)const{ //method0, 重载,所以注意参数和返回值类型
return i<a.i;
}
public:
int i;
};
class comp{
public:
bool operator()(const A& a,const A& b)const{ //method1, 重载,所以注意参数和返回值类型
return a.i<b.i;
}
};
bool funcpComp(const A& a,const A&b){ //method2使用函数指针来指向此比较函数
return a.i<b.i;
}
int main(){
map<A,string> m;
map<A,string,comp> m1;
map<A,string,bool(*)(const A& a,const A& b)>m2(funcpComp);
A a;
A b;
m.insert(make_pair(a, "12"));
m.insert(make_pair(b, "34"));
m1.insert(make_pair(a, "12"));
m1.insert(make_pair(b, "34"));
m2.insert(make_pair(a, "12"));
m2.insert(make_pair(b, "34"));
cout<<m.size()<<" "<<m1.size()<<" "<<m2.size()<<endl;
}