码迷,mamicode.com
首页 > 其他好文 > 详细

Practice6_3_map_sort_by_compareStu

时间:2017-03-04 21:07:38      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:www   并且   maps   void   pair   second   blank   public   include   

 

这个程序也是在解决“invalid operator<”的问题,问题的根因是当两个元素相等时必须返回false才行!!(见这里,和这里

return false; //Should return false if both the vaules are same

这个问题困扰了我一下午,当然下午还在上班,没有全部放在这上面,但是一有时间思绪是在这上面的。

好在,晚上顺利解决了。能够安心做题了,这周的技能练习。

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

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

using namespace std;

/* map和其他容器一样,默认是less<>升序排序的,这对key为整型时默认就行了,
但map的key是结构体的时候就需要自己写operator了,否则会编译不过*/
typedef struct tagStudentInfo
{
    unsigned int stuId;
    string stuName;
}StudentInfo;

string strs[5] = {"huawei", "xiaomi", "meizu", "oppo", "vivo"};

/*
class compStu
{
public:
    int operator()(const StudentInfo &x, const StudentInfo &k) const
    {
        if(k.stuId > x.stuId) return 1;
        else return x.stuName.compare(k.stuName) > 0;//这句写的非常好!!之前也一直在寻找这种写法,它出现了,还是要多读书。。
  }
};*/

struct compStu
{
    int operator()(const StudentInfo &x, const StudentInfo &k) const
    {
        if(k.stuId != x.stuId) 
            return k.stuId > x.stuId;//这里必须是大于,并且return true,原因见参考链接
        else 
            return k.stuName.compare(x.stuName) > 0;//这句写的非常好!!之前也一直在寻找这种写法,它出现了,还是要多读书。。
  }
};

/* 第一种方法,用insert函数插入pair数据*/
void initMapByPair(map<StudentInfo, int, compStu> &mapStu, unsigned int size)
{
    //StudentInfo si = {0, ""}; //两种方式实现初始化,一种是先声明后赋值,另一种直接在循环中初始化。不能混用!!为啥??
    StudentInfo si;
    for(unsigned int i = 0; i < size; i++)
    {
        //StudentInfo si = {5, strs[i]};
        si.stuId = i + 1;
        si.stuName = strs[i];
        mapStu.insert(pair<StudentInfo, int>(si, i + 90));
    }
}

void printMapStu(map<StudentInfo, int, compStu> mapStu)
{
    map<StudentInfo, int, compStu>::iterator it = mapStu.begin();
    for(; it != mapStu.end(); it++)
    {
        cout << it->first.stuId << "," << it->first.stuName << "," << it->second << endl;//使用first,second取出map的key及value
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    map<StudentInfo, int, compStu> mapStudent;//以学生信息映射考试成绩
    initMapByPair(mapStudent, 5);

    printMapStu(mapStudent);
    return 0;
}

运行结果:

1,huawei,90
2,xiaomi,91
3,meizu,92
4,oppo,93
5,vivo,94

Practice6_3_map_sort_by_compareStu

标签:www   并且   maps   void   pair   second   blank   public   include   

原文地址:http://www.cnblogs.com/liuzc/p/6502523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!