multimap(程序设计与算法(一))

本文展示了一个使用C++ multimap容器的示例程序,该程序接收用户输入的学生姓名、ID和分数,然后以分数为键存储学生信息。当用户查询特定分数时,程序返回具有最高ID的相同分数学生的信息。

一、用法

二、应用

#include<iostream>
#include<map>
using namespace std;
struct studentinfo
{
	int id;
	char name[20];
};
struct student   //multimap容器内元素是pair形式
{
	int score;
	studentinfo info;
};
typedef multimap<int, studentinfo> MAP_STD;
int main() 
{
	MAP_STD mp;
	student st;
	char cmd[20];
	while (cin >> cmd)
	{
		if (cmd[0] == 'A')
		{
			cin >> st.info.name >> st.info.id >> st.score;
			mp.insert(make_pair(st.score, st.info));   //使得输入以pair形式存入
		}
		else if (cmd[0] == 'Q')
		{
			int score;
			cin >> score;
			auto p = mp.lower_bound(score);
			if (p != mp.begin())
			{
				--p;
				score = p->first;
				MAP_STD::iterator maxp = p;
				int maxid = p->second.id;
				for (; p != mp.begin() && p->first == score; --p)
				{
					if (p->second.id > maxid)
					{
						maxp = p;
						maxid = p->second.id;
					}
				}
				if (p->first == score)  //即是因为指向begin()跳出,此时仍需比较
				{
					if (p->second.id > maxid)
					{
						maxp = p;
						maxid = p->second.id;
					}
				}
				cout << maxp->second.name << " " << maxp->second.id << " " << maxp->first << endl;
			}
			else  //即p==mp.begin() 没有比其更低的了
				cout << "Nobody" << endl;
		}
	}
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值