C++ Foundation —— (15) C++14 map (Not translated)
»
    C++中的map,默认是TreeMap,所以,对于放入C++中的map需要实现operator <操作符重载。

    map的例子代码:

#include <iostream>
#include <map>
typedef enum{
    UNCONFIRMED=0,
    MALE=1,
    FEMALE=2
}Gender;

using namespace std;
class RowItem{
private:
    int id;
    string name;
    Gender gender;
public:
    RowItem(int id, string name, Gender gender){
        this->id=id;
        this->name=std::move(name);
        this->gender=gender;
    }
    bool operator < (const RowItem& right) const{
        return this->name<right.name;
    }
    void print() const{
        cout<<this->id<<" "<<this->name<<" "<<this->gender<<endl;
    }
};

int main(){
    RowItem rowItem1(1,"NotSortName1",MALE);
    RowItem rowItem2(2,"001SortName2",FEMALE);
    RowItem rowItem3(3,"Name3",MALE);

    map<int,RowItem>idToRowItemMap;
    idToRowItemMap.insert(make_pair(1,rowItem1));
    idToRowItemMap.insert(make_pair(2,rowItem2));
    idToRowItemMap.insert(make_pair(3,rowItem3));

    map<RowItem,int>rowItemToIdMap;
    rowItemToIdMap.insert(make_pair(rowItem1,1));
    rowItemToIdMap.insert(make_pair(rowItem2,1));
    rowItemToIdMap.insert(make_pair(rowItem3,1));

    cout<<"Id To RowItem Map:"<<endl;
    for(auto& pair:idToRowItemMap){
        pair.second.print();
    }

    cout<<"RowItem(sortByName) To Id Map:"<<endl;
    for(auto& pair:rowItemToIdMap){
        pair.first.print();
    }
    return 0;
}
打印结果:
Id To RowItem Map:
1 NotSortName1 1
2 001SortName2 2
3 Name3 1
RowItem(sortByName) To Id Map:
2 001SortName2 2
3 Name3 1
1 NotSortName1 1

«
--Alex.Zhang
--www.v-signon.com Learningers Co-Encouraged
Back
Personal Art: www.up-task.com Unit: Individual
中文 Русский 京ICP备19038994号-2
If the content on this website infringes upon your any rights, please contact me at 1307776259@qq.com for removal