首页 > 文章列表 > C++程序初始化字典

C++程序初始化字典

字典 程序 初始化
148 2023-09-05

C++在同名的字典方面与Python不同,但它具有相似功能的相同数据结构。C++支持映射,可在STL类std::map中使用。映射对象在每个条目中包含一对值,一个是键值,另一个是映射值。键值用于在映射中搜索和唯一标识条目。而映射值不一定是唯一的,键值在映射中必须始终是唯一的。让我们看一下如何使用映射。

首先,让我们看看如何在C++中定义一个映射数据结构。

语法

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

让我们举个例子,看看如何做到这一点−

示例

#include <iostream>
#include <map>

using namespace std;

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

   //inserting two key-value pairs
   myMap.insert({1, "Hello"});
   myMap.insert({2, "World"});

   //displaying the key-value pairs
   for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) {
      cout << itr->first << " " << itr->second << endl;
   }

   return 0;
}

输出

1 Hello
2 World

在C++中,可以以不同的方式初始化地图(Maps)。其算法很简单。

算法

  • 创建地图对象。

  • 在声明对象时为其赋值。

使用初始化列表初始化地图

使用初始化列表初始化一个映射(map)与在C++中初始化一个数组是相同的。我们只需要在声明映射时分配键值对,用大括号括起来,格式为{key, value}。语法如下所示。

语法

#include <map>
map <data_type 1, data_type 2> myMap = {{key1, value1}, {key2, value2}};

示例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};

   //displaying the key-value pairs
   for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) {
      cout << itr->first << " " << itr->second << 'n';
   }

   return 0;
}

输出

1 One
2 Two
3 Three

使用赋值运算符初始化映射

这类似于将值分配给数组中的特定索引。我们没有提及索引,而是将键值放在映射下标中,就像在数组中一样。

语法

#include 
map <data_type 1, data_type 2> myMap;
myMap[key1] = value1;

示例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //declaring the map
   map <int, string> myMap;
   myMap[1] = "One";
   myMap[2] = "Two";
   myMap[3] = "Three";

   //displaying the key-value pairs
   for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) {
      cout << itr->first << " " << itr->second << 'n';
   }

   return 0;
}

输出

1 One
2 Two
3 Three

从另一个地图初始化一个地图

可能需要将一个地图复制到另一个地图中,因此我们可以从另一个地图初始化一个地图。我们通过在声明时将地图对象传递给地图的复制构造函数来利用地图类的复制构造函数。

语法

#include <map>
map <data_type 1, data_type 2> myMap1(myMap2);

示例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //declaring the map
   map <int, string> myMap;
   myMap[1] = "One";
   myMap[2] = "Two";
   myMap[3] = "Three";

   //copying using copy constructor
   map <int, string> myMap2(myMap);

   //displaying the key-value pairs
   for (auto itr = myMap2.begin(); itr != myMap2.end(); ++itr) {
      cout << itr->first << " " << itr->second << 'n';
   }

   return 0;
}

输出

1 One
2 Two
3 Three

结论

C++中的Map是一个有序集合,即Map中的元素按照键值排序。与其他类似的数据结构(例如键值对未排序的无序映射)相比,这使其速度更慢。映射中的所有操作都具有对数复杂度,并且在内存中都以红黑树的形式实现。然而,在实践中,映射非常有用,因为它提供了以键值方式存储数据的极大灵活性。我们已经讨论了初始化地图的所有主要方法;虽然初始化的方法比较多,但这些是最直观的操作方式。