Map uses a custom class pointer as the key

Source: Internet
Author: User
// 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.