python转C++之字典转map

前言

本文主要使用c++的map来描述python的字典数据结构。

一、字典

python中字典是一种可变容器模型(无序),且可存储任意类型对象

# 创建字典
dict0 = dict()
dict1 = {100: 'red', 101: 'yellow', 102: 'blue'}

# 访问字典
print(dict1[101])

# 添加元素
dict1[108] = 'green'
print(108, ':', dict1[108])

# 遍历字典
for key in dict1:
    print(key, ":", dict1[key])

# 修改字典
dict1[101] = 'white'
print(101, ':', dict1[101])

# 合并字典
dict2 = {104: 'pink', 105: 'orange'}
dict1.update(dict2)
print(dict1)

# 键的总数
print("dict1大小为:", len(dict1))

# 判断元素是否存在
if 100 in dict1:
    print("100 in dict1")

# 删除元素
del dict1[102]
print(dict1)

# 清空字典
dict1.clear()

二、map

C++中的map是一种关联式容器,它存储的是键值对的集合。

// 创建
std::map<int, std::string> map1;
std::map<int, std::string> map2 = { {100,"red"},{101,"yellow"},{102,"blue"} };

// 访问
std::cout << map2[101] << std::endl;

// 添加
map2[108] = "green";
std::cout << map2[108] << std::endl;

// 遍历
for (auto it1 : map2)
{
	std::cout << it1.first << ":" << it1.second << std::endl;
}

// 修改
map2[101] = "while";
std::cout << 101 << ":" << map2[101] << std::endl;

// 合并
std::map<int, std::string> map3 = { {104,"pink"},{105,"orange"} };
for (auto it2 : map3)
{
	map2[it2.first] = it2.second;
}

// 长度
std::cout << map2.size() << std::endl;

// 删除
map2.erase(102);
for (auto it : map2)
{
	std::cout << it.first << ":" << it.second << std::endl;
}

// 清空
map2.clear();

总结

本文主要针对python转c++时对字典的常用操作利用map进行简单描述,新人能力有限,如有不足之处欢迎大佬指点纠正。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值