【C++】黑马C++泛型编程和STL技术 (8) STL常用容器 --- map/multimap

3.9 map/multimap 容器

3.9.1 map基本概念

map中所有的元素都是pair,第一个元素为key(键值),起到索引作用,第二个元素为value(实值)。所有的元素会根据元素的键值自动排序

本质上,map/multimap属于关联式容器,底层结构是用二叉树实现。

根据key可以快速找到value值,map容器不允许重复key值元素,而multimap则可以重复key值。

3.9.2 map构造和赋值

构造:

map<T1,T2> mp; 			// 默认构造
map(const map &map);  	// 拷贝构造

赋值:

map& operator=(const map &mp);	 //重载等号操作符

示例:

#include<iostream>
using namespace std;
#include<map>
void printMap(const map<int,int> &m)
{
	for(map<int,int>::const_iterator it = m.begin();it!=m.end();it++)
	{
		cout << "key:" << (*it).first << " "
			<< "value:"<< it->second << endl;
	}
}
void test01()
{
	//创建map容器
	map<int,int> m;
	// 插值
	m.insert(pair<int,int>(1,10)); // 匿名对组
	m.insert(pair<int,int>(3,30)); // 所有元素都是成对出现(键值对),插入数据用对组
	m.insert(pair<int,int>(4,40));
	m.insert(pair<int,int>(2,20));
	m.insert(pair<int,int>(5,50));
	// 输出
	printMap(m);
	// 拷贝构造
	map<int,int> m2(m);
	// 赋值
	map<int,int> m3;
	m3 = m2;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述

3.9.3 map大小和交换

函数原型:

empty();	//判断容器是否为空
size(); 	// 返回容器中元素的数目
swap(mp); // 交换两个集合容器

3.9.4 map插入和删除

函数原型:

insert(elem);	// 插入元素,注意是对组
clear();		// 清空
erase(pos);
erase(beg,end);
erase(key);		// 按照key值删除

示例:

#include<iostream>
using namespace std;
#include<map>
void printMap(const map<int,int> &m)
{
	for(map<int,int>::const_iterator it = m.begin();it!=m.end();it++)
	{
		cout << it->first << " " << it->second << endl;
	}
}
void test01()
{
	map<int,int> m;
	// 插入--- 四种方法
	m.insert(pair<int,int>(1,10));
	m.insert(make_pair(2,20));
	m.insert(map<int,int>::value_type(3,30));
	m[4] = 40;
	// 不建议用于插入数据,主要用于通过key访问value
	cout << m[5] << endl;
	// key为5不存在,就会自动在容器中创建一个key为5,value为0的元素
	cout << m[1] << endl;
	printMap(m);
	// 删除
	cout << "删除后:" << endl;
	m.erase(m.begin());
	m.erase(4);		// 按照key值删除
	printMap(m);
}
int main()
{
	test01();
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述

3.9.5 map查找和统计

根据key值进行查找和统计

函数原型:

find(key);		//	查找key值是否存在,存在返回该键的元素的迭代器,不存在返回map.end()
count(key);		//  统计key的元素个数

找了一圈没找到,就返回最后的位置。根据返回值是否为map.end(),判断是否找到元素。

3.9.6 map排序

默认排序是升序,利用仿函数,就可以将其改为降序

示例:

#include<iostream>
using namespace std;
#include<map>
class myCmp
{
public:
	bool operator()(int v1,int v2)
	{
		return v1 > v2;
	}
};
void test01()
{
	map<int,int,myCmp> m;
	m.insert(make_pair(1,10));
	m.insert(make_pair(2,20));
	m.insert(make_pair(3,30));
	m.insert(make_pair(4,40));
	for(map<int,int,myCmp>::iterator it = m.begin();it!=m.end();it++)
	{
		cout << it->first << " " << it->second << endl;
	}
}
int main()
{
	test01();
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值