c++进阶学习笔记--map

#include<iostream>
#include<map>
#include"student.h"
using namespace std;

//map<键的类型,值的类型> map名;<>中作为键值对
//同时map中要存放pair类型,然后再将pair插入到map中去  pair<键类型,值类型> pair名(键,值);
//再调用 map名.insert(pair名); 函数进行插入,但注意插入map的键是必须可以进行比较大小的

typedef bool(*fun_cmp)(const student&, const student&);//因为写那个函数作为泛型有点长,我们就直接将其替代为fun_cmp
bool stucmp(const student& s1,const student& s2)	//因为student作为键无法直接比较,所以用一个函数指针来作比较
{
	return s1.getId() > s2.getId();			//用student类型中的id来作比较
}


int main()
{
	map<student, double,fun_cmp> stus(stucmp);//这里要加上泛型和函数指针(which is后者stu的括号中的)
	student stu("Sechs", 100);
	pair<student, double> p(stu, 100);
	
	//做好pair和map的准备之后就将pair插入map中
	stus.insert(p);

	//
	stus[stu] = 90;    //这样使用会直接访问到map stus中的stu,并且是会修改的,且如果没有stu,会自动创建一个stu,对应值0

	map<student, double>::iterator it;
	for (it = stus.begin(); it != stus.end(); it++)
	{
		const student& stu = it->first;		//对应map的键
		double score = it->second;			//对应其值
		stu.showname();
		cout << "score:" << score << endl;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值