C++ - map key值比较

 

#include <iostream>
#include <string>
#include <bitset>
#include <map>

using namespace std;

class A
{
public:
        A() { cout << "in A::A()" << endl; }

public:

        // 用户只需要重载这个函数, 就可以进行map的操作。
        bool operator < (const A& a) const
        {
                return (i < a.i);
        }

public:
        int i;
};

int main ()
{
map<A, string> m;

A a;
A b;

m.insert(pair<A, string>(a, "a"));
m.insert(pair<A, string>(b, "b"));
return 0;
}

 

However, if user had not defined the operator <, we can point out a compare function for map definition; there are two methods.

 

1. Define a class which implement a function call operator

2. Use a function pointer which point to a compare function

 

#include <iostream>
#include <string>
#include <bitset>
#include <map>

using namespace std;


class A
{
public:
        A() { cout << "in A::A()" << endl; }

public:
        int i;
};

bool fncomp (const A & lhs, const A & rhs)    // define compare function, as method 2
{
        return lhs.i < rhs.i;
}

class classcomp           // define compare class, as method 1
{
public:

        // 这个操作实际上是一个括号操作符重载, 这样就允许对象classcomp可以像函数那样使用,

        // 其结果是对象classcomp和前面定义的函数可以在一起使用.

        bool operator() (const A & lhs, const A & rhs) const   // the class must has a operator function.
        {
                return lhs.i < rhs.i;
        }
};


int main ()
{
map<A, string, classcomp> m1;                                                  // usage of method 1
map<A, string, bool(*)(const A&,const A&)> m2(fncomp);          // usage of method 2

A a;
A b;

m1.insert(pair<A, string>(a, "a"));
m2.insert(pair<A, string>(b, "b"));
return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值