您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

C++程序初始化字典

2025/5/30 23:24:13发布20次查看
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 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++程序初始化字典的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product