前言
本文主要使用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进行简单描述,新人能力有限,如有不足之处欢迎大佬指点纠正。