📜  C++ STL 中的 Multimap 与 Map 示例(1)

📅  最后修改于: 2023-12-03 15:29:49.966000             🧑  作者: Mango

C++ STL中的 Multimap 与 Map 示例

STL (Standard Template Library) 是C++中的一种标准库,其中包含许多容器和算法来开发高效和可重用的软件。其中之一是map和multimap。

两者都是C++ STL中非常常用的容器,都可以根据键值对(Key-Value Pair)进行操作,但是它们有不同的用途和优缺点。

Map

Map是一种键值对容器,其中每个键值对称为一个项。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

Multimap类似于Map,但可以存储多个具有相同键的项。Multimap并不会根据键值对进行排序,但仍可以根据键名称访问值。以下是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

总的来说,两种容器都非常有用,根据需求选择不同的容器,可以提高程序效率并简化代码。