栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

STL之map容器的讲解(C++)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

STL之map容器的讲解(C++)

以下是对map容器的讲解:
map容器有一个索引值,相当于位置,还有一个就是我们的真值,map容器和set容器一样会自动进行排列,底层也是二叉树。

#include
using namespace std;
#include
void print(map&m)
{
	for (map::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << "key值为:" << (*it).first << " " << "初始化的值为: " << it->second << endl;
	}
	cout << endl;
}
//以下是pair的初始化
void initializepair()
{
	//对组创建的两种方式
	pairp1("小刘", 20);
	cout << "姓名:" << p1.first << " " << " 年龄:" << p1.second << endl;
	pairp2 = make_pair("小王", 26);
	cout << "姓名:" << p2.first << " " << " 年龄:" << p2.second << endl;
}
//以下是map容器的初始化,构造的用法
void test1()
{
	//由于map容器是对组,所以创建的时候需要两个数据类型,且插入数组的时候需要用pair来创建且map容器也会自动进行排列
	mapm;
	m.insert(pair(1, 6));
	m.insert(pair(3, 8));
	m.insert(pair(2, 1));
	m.insert(pair(4, 2));
	print(m);
	mapm2(m);
	print(m2);
	mapm3;
	m3 = m2;
	print(m3);
}
//以下是交换功能的实现和求大小,判空的实现
void test2()
{
	mapm2;
	m2.insert(pair(1, 16));
	m2.insert(pair(3, 18));
	m2.insert(pair(2, 21));
	m2.insert(pair(4, 22));
	if (m2.empty())
	{
		cout << "为空!" << endl;
	}
	else
	{
		cout << "不为空!" << endl;
	}
	cout << "大小为:" << m2.size() << endl;
	mapm3;
	m3.insert(pair(5, 56));
	m3.insert(pair(6, 58));
	m3.insert(pair(7, 51));
	m3.insert(pair(8, 52));
	cout << "未交换前:" << endl;
	print(m3);
	cout << "交换后:" << endl;
	m2.swap(m3);
	print(m3);
}
//以下是插入和删除函数
void test3()
{
	mapm3;
	//m3.insert(2,66);//运行时会报错,错误的方法
	//以下两种就是创建对组的方式进行插入
	m3.insert(pair(1, 10));//相当于用了匿名对象
	m3.insert(make_pair(2, 20));
	m3.insert(map::value_type(3, 30));//不建议使用
	m3[4] = 40;//一般用[]来获取值,不用来进行插入操作。
	print(m3);
	m3.erase(m3.begin());//删除起始位置的元素
	print(m3);
	m3.erase(3);//删除key为3所对应的数值
	print(m3);
	m3.erase(m3.begin(),m3.end());//相当于清空操作
	print(m3);
	m3.clear();
	print(m3);
}
//以下是find函数和统计count函数
void test4()
{
	mapm4;
	m4.insert(pair(1, 11));//相当于用了匿名对象
	m4.insert(make_pair(2, 22));
	m4.insert(map::value_type(3, 33));
	m4[4] = 55;
	m4.insert(pair(3, 88));
	print(m4);
	map::iterator it=m4.find(4);
	if (it != m4.end())
	{
		cout << "找到了且key和值分别为:" << (*it).first << "  " << it->second<b
//	int operator()(int a, int b)
//	{
//		return a > b;
//	}
//};
//void test6()
//{
//
//	mapm6;
//
//	m6.insert(pair(1, 16));
//	m6.insert(pair(3, 18));
//	m6.insert(pair(2, 21));
//	m6.insert(pair(4, 22));
//	for (map::iterator it = m6.begin(); it != m6.end(); it++)
//	{
//		cout << (*it).first << it->second << endl;
//	}
//	cout << endl;
//}
int main()
{
	test1();
	test2();
	test3();
	test4();
	system("pause");
	return 0;
}

希望我的代码能对大家起到一点点的帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/347025.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号