C++ Map容器详解:插入、遍历和输出
#include
#include
using namespace std;
/*
template<typename T1, typename T2>
struct pair
{
T1 first;
T2 second;
};
/
int main()
{ // map<key_t, value_t>
map<string, int> mp;
mp["one"] = 1;
// mp["one"] = 2;
mp.insert(make_pair("one", 2));
mp.insert(make_pair("two", 20));
mp.insert(pair<string, int>("three", 3));
mp.insert(map<string, int>::value_type("four", 4));
/ map<string, int>::iterator it;
for(it = mp.begin(); it != mp.end(); it++) {
cout << "key " << it->first << " value " << it->second << endl;
}
/
/
for(const auto &pr : mp) {
cout << "key " << pr.first << " value " << pr.second << endl;
}*/
for(const auto &[key, value] : mp) {
cout << "key " << key << " value " << value << endl;
}
return 0;
}
解释每行代码内容:1. #include <iostream>: 包含输入输出流的库
2. #include <vector>: 包含向量容器的库
3. #include <stack>: 包含栈容器的库
4. #include <queue>: 包含队列容器的库
5. #include <list>: 包含链表容器的库
6. #include <map>: 包含映射容器的库
7. #include <algorithm>: 包含算法函数的库
using namespace std;: 使用命名空间std,以便直接使用标准库的函数和对象,无需前缀std::map<string, int> mp;: 创建一个名为mp的map容器,其中键为字符串类型,值为整数类型mp["one"] = 1;: 将键为'one'的值设为1mp.insert(make_pair("one", 2));: 插入键为'one'、值为2的键值对到map容器中mp.insert(make_pair("two", 20));: 插入键为'two'、值为20的键值对到map容器中mp.insert(pair<string, int>("three", 3));: 插入键为'three'、值为3的键值对到map容器中mp.insert(map<string, int>::value_type("four", 4));: 插入键为'four'、值为4的键值对到map容器中
20-25. 使用迭代器遍历map容器中的每个键值对,并输出键和值
27-30. 使用范围for循环遍历map容器中的每个键值对,并输出键和值
32-35. 使用结构化绑定和范围for循环遍历map容器中的每个键值对,并输出键和值
return 0;: 返回0,表示程序正常结束
原文地址: https://www.cveoy.top/t/topic/quyI 著作权归作者所有。请勿转载和采集!