📅  最后修改于: 2023-12-03 15:29:49.966000             🧑  作者: Mango
STL (Standard Template Library) 是C++中的一种标准库,其中包含许多容器和算法来开发高效和可重用的软件。其中之一是map和multimap。
两者都是C++ STL中非常常用的容器,都可以根据键值对(Key-Value Pair)进行操作,但是它们有不同的用途和优缺点。
Map是一种键值对容器,其中每个键值对称为一个项。Map使用相应的比较函数对键进行排序,并可以访问键的值。以下是Map的一些用途:
以下是Map的一些优缺点:
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<int, string> mp; // 定义一个map
mp.insert(pair<int, string>(1, "one")); // 插入一个键值对
mp.insert(pair<int, string>(2, "two"));
mp.insert(pair<int, string>(3, "three"));
mp.insert(make_pair(4, "four"));
mp.insert(make_pair(5, "five"));
mp[6] = "six"; // 通过下标方式插入
mp[7] = "seven";
map<int, string>::iterator iter; // 迭代器
for(iter=mp.begin(); iter != mp.end(); iter++)
{
cout<<iter->first<<" "<<iter->second<<endl; // 遍历所有项
}
cout<<endl;
cout<<"Frequency of 3: "<<mp.count(3)<<endl; // 统计键值3的出现频率
cout<<"Frequency of 9: "<<mp.count(9)<<endl; // 统计键值9的出现频率
cout<<"Erasing 4 now"<<endl; // 删除键值4的项
mp.erase(4);
cout<<endl<<"Map after erasing 4 "<<endl;
for(iter=mp.begin(); iter != mp.end(); iter++)
{
cout<<iter->first<<" "<<iter->second<<endl; // 再次遍历所有项
}
return 0;
}
输出:
1 one
2 two
3 three
4 four
5 five
6 six
7 seven
Frequency of 3: 1
Frequency of 9: 0
Erasing 4 now
Map after erasing 4
1 one
2 two
3 three
5 five
6 six
7 seven
Multimap类似于Map,但可以存储多个具有相同键的项。Multimap并不会根据键值对进行排序,但仍可以根据键名称访问值。以下是Multimap的一些用途:
以下是Multimap的一些优缺点:
#include <iostream>
#include <map>
#include <iterator>
using namespace std;
int main()
{
multimap<int, string> mymap; // 定义一个multimap
mymap.insert(make_pair(1, "one"));
mymap.insert(make_pair(2, "two"));
mymap.insert(make_pair(3, "three"));
mymap.insert(make_pair(4, "four"));
mymap.insert(make_pair(5, "five"));
mymap.insert(make_pair(1, "uno")); // 可以插入重复键值对
mymap.insert(make_pair(2, "dos"));
multimap<int, string>::iterator iter;
// 遍历Mmap所有项
for(iter=mymap.begin(); iter != mymap.end(); iter++)
{
cout<<iter->first<<" "<<iter->second<<endl; // 输出键值对
}
cout<<"Item count with key 1: "<<mymap.count(1)<<endl; // 统计键值1的项数
iter = mymap.find(3); // 查找键值3的项
cout<<endl<<"The value found is: "<<iter->second<<endl; // 输出键值3的项
// 删除键值1的项
mymap.erase(1);
cout<<"Item count after deletion: "<<mymap.count(1)<<endl; // 统计键值1的项数
return 0;
}
输出:
1 one
1 uno
2 two
2 dos
3 three
4 four
5 five
Item count with key 1: 2
The value found is: three
Item count after deletion: 0
总的来说,两种容器都非常有用,根据需求选择不同的容器,可以提高程序效率并简化代码。