该程序实现了学生信息到学生成绩的映射,且当map容器的key为结构体时要自己动手重载operator<才行,因为map是排序的,
对于int型默认就行了,但对于结构体map是不知道如何排序的,所以要自己手重载operator<,否则会编译不过。
该程序以重载结构体的operator<操作符实现,下一个程序,单独实现一个比较器,作为map的第三个参数。
经过前面的vector容器练习之后,这些道理和用法都是一样一样的。
// 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;
bool operator < (const tagStudentInfo &stuInfo) const
{
if(stuId != stuInfo.stuId)//按照sduId排序,若stuId相同,则按照stuName排序
{
return stuId < stuInfo.stuId;
}
else
{
return stuName.compare(stuInfo.stuName) < 0;//这句写的非常好!!之前也一直在寻找这种写法,它出现了,还是要多读书。。
}
}
}StudentInfo;
string strs[5] = {"apple", "xiaomi", "meizu", "oppo", "vivo"};
/* 第一种方法,用insert函数插入pair数据*/
void initMapByPair(map<StudentInfo, int> &mapStu, unsigned int size)
{
StudentInfo si = {0, ""}; //两种方式实现初始化,一种是先声明后赋值,另一种直接在循环中初始化。不能混用!!为啥??
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> mapStu)
{
map<StudentInfo, int>::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> mapStudent;//以学生信息映射考试成绩
initMapByPair(mapStudent, 5);
printMapStu(mapStudent);
return 0;
}
运行结果:
1,apple,90
2,xiaomi,91
3,meizu,92
4,oppo,93
5,vivo,94