C++中multimap和map容器及使用

map/multimap容器里存放的都是pair模板类的对象,而且按照first成员从小到大排序。

1. pair模板

pair模板类的定义如下,其中有两个成员变量:first和second:
在这里插入图片描述

2. multimap模板类

template<class Key, class T, class Pred=less<Key>, class A=allocator<T> >
class multimap{
...
typedef pair<const Key,T> value_type;
...
};

可以看到,mutimap中元素都是由pair对象,其中first为关键字,second为值,其类型为Key。在模板类里定义了value_type类型用于创建pair类的对象。

3. multimap的一个例子

这是我根据视频里老师示范的例子,改动了一下。这个例子如下:


一个商品信息录入和查询系统,信息包括:库存数,商品名称,商品价格。
输入格式如下:
添加:ADD num item price;范例:ADD 20 JUICE 3(表示加入20个果汁,单价3元)
查询:QUERY num;范例:QUERY 10(查询所有库存小于10,且价格最高的商品信息,如果有多个商品都满足,则输出全部符合条件的,若没有则输出“Not Found!”)


考虑到multimap中都是pair的对象,只有first和second成员变量,而且查询是以库存为目标,所以我们把库存作为first成员,而把商品名称和价格都放在一个结构体中,共同作为second成员。

  • 建立商品信息类:
class Item {
public:
	struct Item_info {
		string Item_name;
		int Item_price;
	};
	int Item_stock;
	Item_info info;		//	info共同作为pair中的second成员
};
  • 建立multimap容器:
typedef multimap<int, Item::Item_info> ITEM_MAP;
  • 商品信息添加:
		if (cmd == "ADD") {
			cin >> it.Item_stock >> it.info.Item_name >> it.info.Item_price;
			itmp.insert(ITEM_MAP::value_type(it.Item_stock, it.info));	//value_type是pair类
		}
  • 商品信息查询:
		//**查询
		if (cmd == "QUERY") {
			int stock_limit;
			cin >> stock_limit;
			ITEM_MAP::iterator sp = itmp.lower_bound(stock_limit);
			if (sp != itmp.begin()) {
				ITEM_MAP::iterator sp_st=--sp;
				//**寻找库存及价格都相等的商品
				int stock_max = sp->first;
				int price_max = sp->second.Item_price;
				cout << "Find Stock < " << stock_limit << "with max price: " << endl;
				for (;sp!=(itmp.begin())&&(sp->first == stock_max) ;--sp) {
					if (sp->second.Item_price > price_max)
						price_max = sp->second.Item_price;
				}
				for (;sp_st != (itmp.begin()) && (sp_st->first == stock_max)&&(sp_st->second.Item_price==price_max);--sp_st) {
					cout << sp_st->first << " " << sp_st->second.Item_name << " " << sp_st->second.Item_price << endl;
				}
				//for循环终止的原因可能是--sp等于begin,这时候需要判断begin对应的值大小关系
				if (sp == itmp.begin()) {
					if((sp->first == stock_max) && (sp->second.Item_price == price_max))
						cout << sp->first << " " << sp->second.Item_name << " " << sp->second.Item_price << endl;
				}
			}
			else
			{
				cout << "Not Found!" << endl;
			}
			}
  • 运行结果:
    在这里插入图片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章