#include\x3ciostream\x3e\n#include\x3cvector\x3e\n#include\x3cstack\x3e\n#include\x3cqueue\x3e\n#include\x3clist\x3e\n#include\x3cmap\x3e\n#include\x3calgorithm\x3e\n\nusing namespace std;\n/\ntemplate\x3ctypename T1, typename T2\x3e\nstruct pair\n{\n T1 first;\n T2 second;\t\n};\n/\nint main()\n{ // map\x3ckey_t, value_t\x3e\n map\x3cstring, int\x3e mp; \n mp["one"] = 1; \n// mp["one"] = 2; \n mp.insert(make_pair("one", 2));\n mp.insert(make_pair("two", 20));\n mp.insert(pair\x3cstring, int\x3e("three", 3));\n mp.insert(map\x3cstring, int\x3e::value_type("four", 4));\n/* map\x3cstring, int\x3e::iterator it;\n for(it = mp.begin(); it != mp.end(); it++) {\n cout \x3c\x3c "key " \x3c\x3c it->first \x3c\x3c " value " \x3c\x3c it->second \x3c\x3c endl;\n }\n /\n /\n for(const auto &pr : mp) {\n cout \x3c\x3c "key " \x3c\x3c pr.first \x3c\x3c " value " \x3c\x3c pr.second \x3c\x3c endl;\t\n }*/\n for(const auto &[key, value] : mp) {\n cout \x3c\x3c "key " \x3c\x3c key \x3c\x3c " value " \x3c\x3c value \x3c\x3c endl;\t\n }\n return 0;\n}\n这段代码演示了如何使用C++的map容器。map是一种关联容器,它存储了一组键-值对,并按照键的顺序进行排序。在这个例子中,我们创建了一个map,键的类型为string,值的类型为int。\n\n我们使用下标操作符和insert函数向map中插入键-值对。如果键已经存在于map中,下标操作符会更新对应的值,而insert函数会忽略插入操作。我们还可以使用make_pair函数和pair构造函数来创建键-值对,并使用insert函数的value_type参数来插入键-值对。\n\n最后,我们使用迭代器遍历map中的键-值对,并打印出每个键和值。\n\n注意,我们还展示了一种使用C++17的新特性的方法,使用auto和结构化绑定来遍历map中的键-值对。这种方法更简洁,更易读。

C++ map容器详解:存储键值对、排序与遍历

原文地址: https://www.cveoy.top/t/topic/quyc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录