C++ STL map

(一)了解map
map是有序(默认升序)不重复的key-value对(关联容器,不同于顺序容器)
其底层存储结构为红黑树。key不允许重复

(二)Test_Demo

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main()
{
	/*******************************Demo1 define map********************************/
	map<int, string> m;
	map<int, string> m1{ {1, "log1"}, {2, "log2"} };
	map<int, string> m2(m1);
	map<int, string> m3 = { {3, "log3"}, {2, "log2"} };
	
	/*******************************Demo2 options***********************************/
	//遍历:正反向,const,数组
	cout << "m1:" << endl;
	for (map<int, string>::iterator it = m1.begin(); it != m1.end(); ++it) {
		cout << it->first << "," << it->second << endl;
	}

	//map是有序(默认升序)不重复的key-value对(关联容器,不同于顺序容器),输出是升序输出
	cout << "m3:" << endl;
	for (map<int, string>::iterator it = m3.begin(); it != m3.end(); ++it) {
		cout << it->first << "," << it->second << endl;//有序特性
	}

	//for (int i = 0; i < m3.size(); ++i) {
	//	cout << m3[i] << endl;//有序特性
	//}

	//插入
	cout << "第一种插入方式:pair" << endl;
	auto status = m1.insert(pair<int, string>(3, "log1"));
	if (status.second == true) {
		cout << "insert successful!" << endl;
	}
	status = m1.insert(pair<int, string>(3, "log1"));
	if (status.second == false) {//不重复特性
		cout << "insert failed!" << endl;
	}
	for (map<int, string>::iterator it = m1.begin(); it != m1.end(); ++it) {
		cout << it->first << "," << it->second << endl;
	}

	cout << "第二种插入方式:map<int, string>::value_type" << endl;
	status = m1.insert(map<int, string>::value_type (4, "log4"));
	if (status.second == true) 
		cout << "insert successful!" << endl;
	else
		cout << "insert failed!" << endl;
	for (map<int, string>::iterator it = m1.begin(); it != m1.end(); ++it) {
		cout << it->first << "," << it->second << endl;
	}
	cout << "第三种插入(修改)方式:下标" << endl;
	m1[2] = ("log111"); //即使重复也会插入成功,但是会覆盖掉原有的数据(谨慎使用)
	for (map<int, string>::iterator it = m1.begin(); it != m1.end(); ++it) {
		cout << it->first << "," << it->second << endl;
	}

	//删除
	m1.erase(1); 
	auto m_clone = m1;//拷贝构造
	m1.clear();
	if (m1.empty())
		cout << "m1 is empty!" << endl;
	for (map<int, string>::iterator it = m_clone.begin(); it != m_clone.end(); ++it) {
		cout << it->first << "," << it->second << endl;
	}

	//查找数据
	auto it = m_clone.find(2); //若查找一个不存在的key,会发生运行时错误
	cout << it->first << "," << it->second << endl;
	//m_clone.lower_bound();
	//m_clone.upper_bound();

	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值