C++ - map key值比较

 

#include
#include
#include
#include

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

A a;
A b;

m.insert(pair(a, "a"));
m.insert(pair(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
#include
#include
#include

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 m1;                                                  // usage of method 1
map m2(fncomp);          // usage of method 2

A a;
A b;

m1.insert(pair(a, "a"));
m2.insert(pair(b, "b"));
return 0;
}

 

你可能感兴趣的:(C/C++,c++,string,function,class,include,user)