用 C++ 程序创建空字典


映射是 C++ 中的数据结构,可以在 STL 类 std::map 中找到。它类似于我们在 Python 中看到的字典。映射对象中的每个条目都有一对值,其中之一是键值,另一个是映射值。使用键值查找和唯一标识映射中的条目。映射中的键值必须始终唯一,但不需要映射值唯一。在本文中,我们重点介绍创建空映射对象。

创建空映射

我们只创建一个映射对象,结果就是一个空映射。语法如下。

语法

#include <map>
map <data_type 1, data_type 2> myMap;

我们来看一个示例 −

示例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <int, string> myMap;

   //displaying the contents, it returns nothing as it is empty
   for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) {
      cout << itr->first << " " << itr->second << endl;
   }

   return 0;
}

输出

运行代码不会显示任何内容,因为映射为空。

创建零初始化映射

仅当映射的值类型为整数时才可执行此操作。即使我们引用映射中没有的键,返回的值也是 0。

语法

#include <map>
map <data_type 1, int> myMap;

示例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <string, int> myMap;

   //displaying the contents, it returns 0 as it is empty
   for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) {
      cout << itr->first << " " << itr->second << endl;
   }
   cout<< myMap["test"] << endl;

   return 0;
}

输出

0

结论

映射是 C++ 中的有序集合,这意味着元素根据其键值进行排序。映射是在内存中使用红黑树实现的。当初始化映射对象时,所有映射都是空的,但零初始化映射仅在映射值类型为整数时可用。

更新于: 13-12-2022

610 次浏览

开启你的 职业生涯

完成课程获取认证

开始学习
广告
© . All rights reserved.