Practice6_1_map_sort_by_comparator

上一个程序中说——“

该程序以重载结构体的operator<操作符实现,下一个程序,单独实现一个比较器,作为map的第三个参数。

经过前面的vector容器练习之后,这些道理和用法都是一样一样的。”

经过实际操作才发现,并不一样,而且很不一样,遇到了问题,该问题是:

“请问这个程序怎么遍历输出呢?
“第二种:仿函数的应用,这个时候结构体中没有直接的小于号重载,程序说明”
map加了sort参数后,就不能用迭代器了,一直编译不过” 

遗憾的是,从昨天晚上到现在一共花了五六个小时才调试出来,而且目前初始化和迭代器遍历都是在main函数中,按照单一职责原则,抽
象隔离开来还是有问题,编译虽然没有了语法及语义错误,但检查operator函数时报“invalid operator<”错误,程序崩了。下午找出原
因。下一个程序中解决该问题,并实现高内聚。

一个感悟就是,单独实现比较器,远远不如在struct中实现operator简单又方便,why not?!  

// Practice6_map_sort_by_comparator.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <map>
#include <string>
#include <iostream>

using namespace std;

typedef struct tagStudentInfo
{
       int      stuId;
       string   stuName;
}StudentInfo; 

/* 两种方式实现操作符函数,一种是struct,另一种是class加public
struct CompareStu
{
    int operator()(const StudentInfo &x, const StudentInfo &k) const{
    if(k.stuId > x.stuId) return 1;//这里必须是大于,并且return true,原因见参考链接
    else return x.stuName.compare(k.stuName) > 0;
  }
};*/

/* 另一种是class加public*/
class CompareStu
{
public:
    int operator()(const StudentInfo &x, const StudentInfo &k) const{
    if(k.stuId > x.stuId) return 1;//这里必须是大于,并且return true,原因见参考链接
    else return x.stuName.compare(k.stuName) > 0;
  }
};

int main()
{
       map<StudentInfo, int, CompareStu> mapStudent;
       StudentInfo studentInfo;
       studentInfo.stuId = 1;
       studentInfo.stuName = "student_bone";
       mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));
       studentInfo.stuId = 2;
       studentInfo.stuName = "student_atwo";
        mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));

        map<StudentInfo, int, CompareStu>::iterator iter= mapStudent.begin();
        for(; iter != mapStudent.end(); iter++)
        {
            cout << iter->first.stuId << "," << iter->first.stuName << "," << iter->second << endl;
        }
}

参考:这里

原文地址:https://www.cnblogs.com/liuzc/p/6500940.html