排序问题,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;
}
}

最新文章

  1. (转)C# foreach 中获取索引index的方法
  2. 在JSP页面中输出字符&quot; * &quot;组成的金字塔
  3. Mapper类/Reducer类中的setup方法和cleanup方法以及run方法的介绍
  4. Radiobutton编辑
  5. glsl计算sprite的亮度饱和度对比度
  6. Junit单元测试学习笔记一
  7. SQL Server调优系列进阶篇 - 如何重建数据库索引
  8. python 实现对象模型
  9. Python BeautifulSoup4 使用指南
  10. 找到了解决Elite多媒体键失效的问题
  11. Lucene之删除索引
  12. 京东评论情感分类器(基于bag-of-words模型)
  13. ecos的app机制
  14. c++实现 给定直角停车位两个点,求取剩余两点坐标。
  15. 同一个windows server 部署多个tomcat
  16. jenkins+sonarQube代码质量扫描 并排除指定的目录
  17. 欧拉函数(C语言实现)
  18. JS实现品字布局
  19. webpack 创建vue项目过程中遇到的问题和解决方法
  20. LOJ#2444. 「NOI2011」阿狸的打字机

热门文章

  1. TCP粘包分析与处理
  2. ecshop的模板文件中如何判断用户是否登录
  3. 使用Transaction访问数据库(C#,TransactionScope,.NET 2.0)
  4. Oracle方向
  5. ASP.NET MVC 学习之路-2
  6. C#核编之System.Environment类
  7. VB.Net常用数学函数整理
  8. 让Linux修改IP、DNS等可以更简单
  9. 剑指offier77页
  10. Java Class类以及获取Class实例的三种方式