stl之map 排序
2024-10-19 06:20:15
排序问题,STL中默认是采用小于号来排序的,因为设置int等类型做key,它本身支持小于号运算,在一些特殊情况,比如关键字是一个结构体,涉及到排序就会出现问题,因为它没有小于号操作,insert等函数在编译的时候过不去,下面给出两个方法解决这个问题:
第一种:小于号重载,程序举例
#include <map>
#include <string>
using namespace std;
typedef struct tagStudentInfo
{
int nID;
string strName;
}StudentInfo, *PStudentInfo; //学生信息 int main()
{
int nSize; //用学生信息映射分数
map<StudentInfo, int>mapStudent;
map<StudentInfo, int>::iterator iter;
StudentInfo studentInfo;
studentInfo.nID = ;
studentInfo.strName = “student_one”;
mapStudent.insert(pair<StudentInfo, int>(studentInfo, ));
studentInfo.nID = ;
studentInfo.strName = “student_two”; mapStudent.insert(pair<StudentInfo, int>(studentInfo, ));
for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++)
cout<<iter->first.nID<<endl<<iter->first.strName<<endl<<iter->second<<endl;
}
//以上程序是无法编译通过的,只要重载小于号,就OK了,如下: typedef struct tagStudentInfo
{
int nID;
string strName;
Bool operator < (tagStudentInfo const& _A) const
{
//这个函数指定排序策略,按nID排序,如果nID相等的话,按strName排序
if(nID < _A.nID) return true;
if(nID == _A.nID) return strName.compare(_A.strName) < ;
return false;
}
}StudentInfo, *PStudentInfo; //学生信息
第二种:仿函数的应用,这个时候结构体中没有直接的小于号重载,程序说明
#include <map>
#include <iostream>
#include <string>
using namespace std; typedef struct tagStudentInfo
{
int nID;
string strName;
}StudentInfo, *PStudentInfo; //学生信息 class sort{
public:
bool operator() (StudentInfo const & _A, StudentInfo const & _B) const
{
if(_A.nID < _B.nID){
return true;
}else if (_A.nID == _B.nID){
return _A.strName.compare(_B.strName) < ;
}
return false;
}
}; int main()
{
int nSize; //用学生信息映射分数
map<StudentInfo, int, sort> mapStudent;
StudentInfo studentInfo;
studentInfo.nID = ;
studentInfo.strName = "student_one"; mapStudent.insert(pair<StudentInfo, int>(studentInfo, ));
studentInfo.nID = ;
studentInfo.strName = "tudent_two";
mapStudent.insert(pair<StudentInfo, int>(studentInfo, )); std::map<StudentInfo, int, sort>::iterator it;
for(it = mapStudent.begin(); it != mapStudent.end(); it++){
std::cout << it->second << std::endl;
}
}
最新文章
- (转)C# foreach 中获取索引index的方法
- 在JSP页面中输出字符"; * ";组成的金字塔
- Mapper类/Reducer类中的setup方法和cleanup方法以及run方法的介绍
- Radiobutton编辑
- glsl计算sprite的亮度饱和度对比度
- Junit单元测试学习笔记一
- SQL Server调优系列进阶篇 - 如何重建数据库索引
- python 实现对象模型
- Python BeautifulSoup4 使用指南
- 找到了解决Elite多媒体键失效的问题
- Lucene之删除索引
- 京东评论情感分类器(基于bag-of-words模型)
- ecos的app机制
- c++实现 给定直角停车位两个点,求取剩余两点坐标。
- 同一个windows server 部署多个tomcat
- jenkins+sonarQube代码质量扫描 并排除指定的目录
- 欧拉函数(C语言实现)
- JS实现品字布局
- webpack 创建vue项目过程中遇到的问题和解决方法
- LOJ#2444. 「NOI2011」阿狸的打字机