STL中 map的用法

来源:互联网 发布:大唐 数据所 副所长 编辑:程序博客网 时间:2024/06/05 00:18

STL的排序问题,STL中默认是采用小于号来排序的,关键字是int型,它本身支持小于号运算,可以进行map的插入操作,但是一些其他的情况下,比如关键字是一个结构体,涉及到排序就会出现问题,因为它没有小于号操作,insert等函数在编译的时候过不去,下面给出两个方法解决这个问题
第一种:小于号重载,程序举例

#include<map>#include<iostream>#include<string>using namespace std;typedef struct Student{    int id;    string name;    bool operator<(Student const&A)const    {        if(id<A.id)            return true;        else if(id==A.id)            return name.compare(A.name)<0;        else            return false;    }}student;void main(){    map<student,int>mapstu;     student student1,student2;    student1.id=20;    student1.name="zhang";    student2.id=20;    student2.name="chen";    mapstu.insert(pair<student,int>(student1,92));    mapstu.insert(pair<student,int>(student2,80));      for(auto i:mapstu)        cout<<i.first.name<<endl;}

第二种:仿函数的应用,这个时候结构体中没有直接的小于号重载,程序说明

#include<map>#include<iostream>#include<string>using namespace std;typedef struct Student{    int id;    string name;}student;class sort{public:    bool operator()(Student const&A,Student const &B)const    {        if(A.id<B.id)            return true;        else if(A.id==B.id)            return A.name.compare(B.name)<0;        return false;    }};void main(){    map<student,int,sort>mapstu;        student student1,student2;    student1.id=20;    student1.name="zhang";    student2.id=10;    student2.name="chen";    mapstu.insert(pair<student,int>(student1,92));    mapstu.insert(pair<student,int>(student2,80));      for(auto i:mapstu)        cout<<i.first.name<<endl;}
0 0
原创粉丝点击