STL中 map的用法

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值