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
- STL中map的用法
- STL中MAP的用法
- STL 中 map 的用法
- STL中map的用法
- STL 中map的用法
- STL中 map的用法
- STL中map的用法
- STL中map用法
- STL中map用法
- STL中map用法
- STL中map的用法剖析
- C++中STL的map用法
- STL 中map的用法(精华版)
- STL中map的用法详解
- C++ STL 中map的一些用法
- 详解STL中map的用法
- 关于STL中map的一些用法
- STL 中map 容器的基本用法
- poj 3984 迷宫问题(BFS+回溯)
- 文件的存取
- UML图
- HDU 4229 Vive la Difference!
- Android Http请求框架二:xUtils 框架网络请求
- STL中 map的用法
- SecureCRT上传、下载文件命令sz与rz用法实例
- GraphX 实现K-Core
- CF 567B(Berland National Library-看成折线图)
- vc屏幕截图实现
- Spring下@Resource, @Autowired和@Inject的区别与联系
- Windows(2003、xp)下配置NTP时间服务器
- C++内存管理
- Android 自定义View (一)