C++语言STL库中unordered_map容器的基本用法

 时间:2026-02-12 03:31:51

1、头文件的声明。

头文件的话,这里我们可以声明一种万能头文件,这样就能直接使用unordered_map这一容器了。

#include<bits/stdc++.h>

C++语言STL库中unordered_map容器的基本用法

2、变量定义

unordered_map这一类型的变量可以使用如下格式进行定义,

unordered_map<第一变量类型,第二变量类型> 变量名;

例如:unordered_map<string,int> umap;

C++语言STL库中unordered_map容器的基本用法

3、元素插入

可以使用两种方法网unordered_map中插入数值。

第一种:使用操作符[]直接插入

例如:

umap["a1"]=2;

umap["a3"]=7;

umap["a2"]=5;

C++语言STL库中unordered_map容器的基本用法

4、第二种:使用insert 方法插入数值

例如:

umap.insert(make_pair("e",7));

C++语言STL库中unordered_map容器的基本用法

5、数值搜索

使用find方法进行数值搜索。

例如:

string key="a3";

    if (umap.find(key)==umap.end())

      cout<<key<<"Not found  "<<endl;

    else

      cout<<"found  "<<key<<endl;

C++语言STL库中unordered_map容器的基本用法

6、数值遍历

与其他STL库中的容器类似,可以使用嵌套的类iterator进行循环遍历。

例如:

unordered_map<string,int>::iterator i;

    cout<<"All value"<<endl;

    for (i=umap.begin();i!=umap.end();i++)

      cout<<i->first<<" "<<i->second<<endl;

C++语言STL库中unordered_map容器的基本用法

7、最后一步提供以上几部的代码提供参考。

#include <iostream>

#include<bits/stdc++.h>

using namespace std;

int main()

{

    unordered_map<string,int> umap;

    //insert value by operator []

    umap["a1"]=2;

    umap["a3"]=7;

    umap["a2"]=5;

    //insert value by insert function

    umap.insert(make_pair("e",7));

    string key="a3";

    if (umap.find(key)==umap.end())

      cout<<key<<"Not found  "<<endl;

    else

      cout<<"found  "<<key<<endl;

    unordered_map<string,int>::iterator i;

    cout<<"All value"<<endl;

    for (i=umap.begin();i!=umap.end();i++)

      cout<<i->first<<" "<<i->second<<endl;

    return 0;

}

C++语言STL库中unordered_map容器的基本用法

  • 福昕阅读器全屏导航设置显示标签栏流程
  • matlab交互式程序设计示例:[6]GUI界面编程1
  • 如何在Tecplot截取不同变量的云图分布
  • simulink:[1]simulink数字滤波器在哪里?
  • Visio怎样用图标标记形状
  • 热门搜索
    什么是世博会 school是什么意思英语 茶盘什么材质的好 一朵玫瑰代表什么 警察蜀黍是什么意思 撸管是什么意思 眼罩什么牌子好 什么是生态平衡 流星雨什么时候出现 我的世界萤石有什么用