Map/multimap键值对容器
·
一,意义
在 C++ 中,<map> 是标准模板库(STL)的一部分,它提供了一种关联容器,用于存储键值对(key-value pairs),类似python能按照键值自动排序字典。
map 容器中的元素是按照键的顺序自动排序的,这使得它非常适合需要快速查找和有序数据的场景
二,用法
#include<map>
#include<algorithm>
#include<iostream>
using namespace std;
void printmap(map<int,int>&m) {
for (map<int, int> ::iterator i = m.begin(); i != m.end(); i++) { //map<>::iterator 是用于遍历容器的迭代器
cout << "key = " << (*i).first << " value = " << (*i).second << endl;
}
}
int main() {
map<int,int> m;
m[3] = 2; //赋值操作,myMap[key] = value;
m.insert(pair<int, int>(2, 4)); //赋值操作
printmap(m);
return 0;
}

结果自动排序
#include<map>
#include<algorithm>
#include<iostream>
#include<string>
using namespace std;
void printmap(map<int,int>&m) {
for (map<int, int> ::iterator i = m.begin(); i != m.end(); i++) { //map<>::iterator 是用于遍历容器的迭代器
cout << "key = " << (*i).first << " value = " << (*i).second << endl;
}
}
int main() {
map<std::string, int> employees;
// 插入员工信息
employees["Dlice"] = 30;
employees["Aob"] = 25;
employees["Charlie"] = 35;
// 遍历 map 并打印员工信息
for (map<string, int>::iterator it = employees.begin(); it != employees.end(); ++it) {
cout << it->first << " is " << it->second << " years old." << endl;
}
return 0;
}
结果同样自动排序
三,进阶用法

更多推荐


所有评论(0)