// Code first
# Pragma once // if you want to use a class as the key, you must overload the <operator or provide a // you can also use a pointer as the key. However, you must provide your own comparison method class cbase {public: explicit cbase (int );~ Cbase (void); Private: int M_a; public: int get () const {return M_a;} public: // as a member function, you only need to input a reference to another object, because it is already an object 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;}
If you want to use a custom class as the key, you must implement <operator overload,
If a pointer is used as the key, you must provide a function-like template that is introduced when the map type is declared.