C++ map容器

通俗一点讲map其实就是python的字典(学会python字典 == c++_map)!!!

map和unordered_map都是C++中的关联容器,用于存储键值对。其主要区别在于底层实现方式和性能表现。

1、底层实现方式

map内部使用红黑树(一种自平衡二叉查找树)来实现,而unordered_map则使用哈希表来实现。这意味着,在map中,元素是按照键的大小进行有序排列的,而在unordered_map中,则不保证元素的顺序。

2、性能表现

当需要有序地遍历元素时,map的性能比unordered_map更好。但是,当需要快速查找特定的元素时,unordered_map通常比map更快。原因在于,map在插入和删除操作时需要维护红黑树的平衡,而unordered_map则只需要计算哈希值并将元素放入相应的桶中即可。

3、用途

由于map可以保证元素的有序性,所以适合用于需要有序的情况下,例如按照键排序输出元素、寻找最小值/最大值等。而unordered_map则适合用于需要快速查找元素的情况下,例如查找是否存在某个键值对、统计某个值出现的次数等。

总之,选择map还是unordered_map取决于具体的需求。如果需要有序地处理元素,则应该使用Map;如果需要快速查找元素,则可以使用unordered_map。

1.写入数据 && 读取数据

cpp 复制代码
#include <iostream>
#include <algorithm>
#include <map>
#include <unordered_map>
using namespace std;

map<string,int> vm;

int main()
{
	// 插入数据
	// key = age  value = 18
	//方法1
	vm["age"] = 18; 
	//方法2
	vm.insert(pair<string,int>("id",123456));
	
	//读取数据
	//方法1
	map<string,int>::iterator it;
	
	for(it = vm.begin();it!=vm.end();it++)
	{
		cout<<it->first<<" "<<it->second<<endl;
	}
	
	//方法2
	for(auto it = vm.begin();it!=vm.end();it++)
	{
		cout<<it->first<<" "<<it->second<<endl;
	}
	
	//方法3
	
	for(auto it:vm)
	{
		cout<<it.first<<" "<<it.second<<endl;
	}
	
	return 0;
}

2.删除数据

cpp 复制代码
#include <iostream>
#include <map>
#include <algorithm>

using namespace std;

map<string,int> vm = {{"xxw",18},{"xm",19},{"bj",14}};

int main()
{
	// 删除指定元素
	map<string,int>::iterator t1;
	t1 = vm.find("xm"); // "xm"为key
	vm.erase(t1);
	
	
	for(auto it:vm)
		cout<<it.first<<" "<<it.second<<endl;

	return 0;
}

3.查找 && 删除

cpp 复制代码
#include <iostream>
#include <unordered_map>
#include <algorithm>
using namespace std;

unordered_map<string, int> vmu = {{"xxw", 18}, {"asd", 19}, {"rty", 45}};

int main() 
{
	// 查找
	unordered_map<string, int>::iterator it;

	string name;
	printf("请输入要查早的key:");
	cin >> name;

	it = vmu.find(name);

	if (it != vmu.end()) {
		cout << "找到了\n";
	} else {
		cout << "抱歉 没找到!" << endl;
	}
	
	printf("-----------------------------------\n");
	//删除_直接通过key来删除
	
	vmu.erase("xxw");
	
	printf("删除之后:\n");
	for(auto it:vmu)
		cout<<it.first<<" "<<it.second<<endl;
	
	return 0;
}
相关推荐
liulilittle5 分钟前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
88号技师12 分钟前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
勤奋的知更鸟18 分钟前
Java 编程之模板方法模式
java·开发语言·模板方法模式
ゞ 正在缓冲99%…40 分钟前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
十年编程老舅1 小时前
跨越十年的C++演进:C++20新特性全解析
c++·c++11·c++20·c++14·c++23·c++17·c++新特性
上单带刀不带妹1 小时前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架
-凌凌漆-2 小时前
【Qt】QStringLiteral 介绍
开发语言·qt
程序员爱钓鱼2 小时前
Go语言项目工程化 — 常见开发工具与 CI/CD 支持
开发语言·后端·golang·gin
努力写代码的熊大2 小时前
单链表和双向链表
数据结构·链表