这个程序也是在解决“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] = {"iphone", "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,iphone,90
2,xiaomi,91
3,meizu,92
4,oppo,93
5,vivo,94