C++ Map Key值的比较操作

一. 数据结构:

     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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值