C++程序使用字典字面量创建字典
C++ 中没有字典,但它有一个类似的结构叫做 map。map 的每个条目包含一对值,分别是键和映射值。键值用于索引每个条目,而映射值是与键关联的值。键是唯一的,但映射值可能唯一也可能不唯一。在本文中,我们将了解如何初始化 map 对象并从另一个 map 对象创建它。
创建空 map
要创建 map 对象,我们需要导入 STL 类 std::map。当我们创建 map 对象时,会创建一个空 map。需要注意的是,在创建 map 对象时,我们必须指定键和映射值的类型。
语法
#include <map> map <data_type 1, data_type 2> map_name;
让我们来看一个例子 -
示例
#include <iostream>
#include <map>
using namespace std;
int main() {
//initialising the map
map <string, string> mmap;
//inserting some values
mmap.insert({"Fruit", "Mango"});
mmap.insert({"Tree", "Oak"});
mmap.insert({"Vegetable", "Eggplant"});
//displaying the contents
for (auto itr = mmap.begin(); itr != mmap.end(); ++itr) {
cout << itr->first << ": " << itr->second << endl;
}
return 0;
}
输出
Fruit: Mango Tree: Oak Vegetable: Eggplant
从另一个 map 创建 map
在某些情况下,我们可能需要复制 map 或需要保留其值。为此,我们可以使用 map 类的复制构造函数从另一个 map 创建 map。我们需要确保两个 map 对象的数据类型匹配。
语法
#include <map> map <data_type 1, data_type 2> map_name1; map <data_type 1, data_type 2> map_name2(map_name1);
示例
#include <iostream>
#include <map>
using namespace std;
int main() {
//initialising the map
map <string, string> mmap = {{"Fruit", "Litchi"}, {"Tree", "Birch"}, {"Vegetable", "Potato"}};
//copy the elements using the copy constructor
map <string, string> copyMap(mmap);
//displaying the contents
for (auto itr = copyMap.begin(); itr != copyMap.end(); ++itr) {
cout << itr->first << ": " << itr->second << endl;
}
return 0;
}
输出
Fruit: Litchi Tree: Birch Vegetable: Potato
结论
map 是 C++ 中的有序集合,这意味着元素根据其键值排序。map 在内存中使用红黑树实现,并为所有操作提供对数时间复杂度。在本文中,我们了解了如何使用复制构造函数创建 map 对象的副本。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP