首先,让我们看看如何在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 hello2 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 one2 two3 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 one2 two3 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 one2 two3 three
结论c++中的map是一个有序集合,即map中的元素按照键值排序。与其他类似的数据结构(例如键值对未排序的无序映射)相比,这使其速度更慢。映射中的所有操作都具有对数复杂度,并且在内存中都以红黑树的形式实现。然而,在实践中,映射非常有用,因为它提供了以键值方式存储数据的极大灵活性。我们已经讨论了初始化地图的所有主要方法;虽然初始化的方法比较多,但这些是最直观的操作方式。
以上就是c++程序初始化字典的详细内容。
