C++中MapDemo

Hello,大家好,我是爱吃香蕉的猴子,写写C++中Map的使用

//map 相对于 set 区别,map 具有键值和实值,所有元素根据键值自动排序
//pair 的第一元素被称为键值,第二元素被称为实值。map 也是以红黑树为底层实现机制。

//对组
//对组(pair)将一对值组合成一个值,这一对值可以具有不同的数据类型,两个值可以分别用pair的两个公有函数first和second访问

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <map>
using namespace std;

//map容器初始化
void test01() {

	//map容器模板参数,第一个参数key的类型,第二参数value类型
	map<int, int> mymap;

	//插入数据  pair.first key值 piar.second value值
	//第一种
	pair<map<int, int>::iterator, bool> ret = mymap.insert(pair<int, int>(10, 10));
	if (ret.second) {
		cout << "第一次插入成功!" << endl;
	}
	else {
		cout << "插入失败!" << endl;
	}
	ret = mymap.insert(pair<int, int>(10, 20));
	if (ret.second) {
		cout << "第二次插入成功!" << endl;
	}
	else {
		cout << "插入失败!" << endl;
	}
	//第二种
	mymap.insert(make_pair(20, 20));
	//第三种
	mymap.insert(map<int, int>::value_type(30, 30));
	//第四种
	mymap[40] = 40;
	mymap[10] = 20;
	mymap[50] = 50;
	//发现如果key不存在,创建pair插入到map容器中
	//如果发现key存在,那么会修改key对应的value

	//打印
	for (map<int, int>::iterator it = mymap.begin(); it != mymap.end(); it++) {
		// *it 取出来的是一个pair
		cout << "key:" << (*it).first << " value:" << it->second << endl;
	}

	//如果通过【】方式去访问map中一个不存在key,
	//那么map会将这个访问的key插入到map中,并且给value一个默认值
	cout << " mymap[60]: " << mymap[60] << endl;

	//打印
	for (map<int, int>::iterator it = mymap.begin(); it != mymap.end(); it++) {
		// *it 取出来的是一个pair
		cout << "key:" << (*it).first << " value:" << it->second << endl;
	}

}


int main(void)
{
	test01();
}
                                    Code的搬运工V1.0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值