map中使用自定义类指针作为key

//先上代码

#pragma once
//想用类作为key,必须重载<运算符 或者提供
//想用指针作为key,也是可以的,不过要自己提供仿函数
class CBase
{
public:
    explicit CBase(int a);
    ~CBase(void);
private:
    int m_a;
public:
    int get() const{return m_a;}
public:
    //作为成员函数,只需要传入另外一个对象的引用即可,因为自己已经是个对象了
    bool operator < ( const CBase& b ) const
    {
        return ( this->m_a < b.m_a );
    }
};

template<class _Ty>
struct less2
{
    bool operator()(const _Ty& _Left, const _Ty& _Right) const
    {
        return _Left->get() > _Right->get();
    }
};

#include "Base.h"

CBase::CBase(int a)
{
    m_a = a;
}

CBase::~CBase(void)
{
}

#include "Base.h"
#include <map>
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    map<CBase*,int,less2<CBase*>> b_i_map;
    CBase* a = new CBase(1);
    CBase* b = new CBase(2);
    CBase* c = new CBase(3);
    CBase* d = new CBase(4);
    b_i_map.insert(make_pair<CBase*,int>(a,1));
    b_i_map.insert(make_pair<CBase*,int>(b,2));
    b_i_map.insert(make_pair<CBase*,int>(c,3));
    b_i_map.insert(make_pair<CBase*,int>(d,4));
    for ( map<CBase*,int,less2<CBase*>>::iterator it = b_i_map.begin();
        it != b_i_map.end(); it++ )
    {
        cout << (*it).first->get() <<" " <<(*it).second <<endl;
    }
    cout <<endl;
    for ( map<CBase*,int,less2<CBase*>>::iterator it = b_i_map.begin();
        it != b_i_map.end(); it++ )
    {
        delete (*it).first;
    }
    b_i_map.clear();
    return 0;
}
这时如果想用自定义类作为key的必须要实现 < 运算符重载,

如果是使用指针作为key,必须提供一个仿函数模板,在声明map类型时引入。

下面举例说明一下,自定义结构作为map的key时重载 <运算符的实现,可以参考下

typedef struct tagUniqueBoard
{
    int m_uShelf;
    int m_uSlot;
    std::string m_strBoardName;
    std::string m_strNEid;
    bool operator < (const tagUniqueBoard& b) const
    {
        if( m_uShelf != b.m_uShelf)
        {
            return m_uShelf < b.m_uShelf;
        }
        else if( m_uSlot != b.m_uSlot)
        {
            return m_uSlot < b.m_uSlot;
        }
        else if( m_strBoardName != b.m_strBoardName)
        {
            return m_strBoardName < b.m_strBoardName;
        }
        else if( m_strNEid != b.m_strNEid)
        {
            return m_strNEid < b.m_strNEid;
        }
        return false;
    }
}UniqueBoard;




猜你喜欢

转载自blog.csdn.net/zipper9527/article/details/7556775
今日推荐