C++哈希表

哈希表教程

目录

  1. 哈希表是什么
  2. 怎么用哈希表
  3. 插入键值对
  4. 查找元素
  5. 删除元素
  6. 遍历哈希表
  7. count检查是否存在某个键

怎么用哈希表

1.包含头文件

首先,你需要包含 unordered_map 的头文件:

c 复制代码
#include<unordered_map>

2.创建哈希表

c 复制代码
std::unordered_map<KeyType,ValueType>hashTable

KeyType是键的类型,ValueType是值的类型

例:如果想存储 键:字符串,值:整数

c 复制代码
std::unordered_map<std::string,int>hashTable

前面如果写了 using namespace std; ,这里可以不用写std::

插入键值对

用 insert 方法或 \[\] 操作符来插入键值对:

c 复制代码
//用insert方法
hsahTable.insert(std::make_pair("apple",1));

//用[]操作符,如果键不存在,会自动创建一个键
hashTable["banana"]=2;
//hashTable["键"]=值;

查找元素

用 find 方法或 \[\] 操作符来查找元素:

c 复制代码
//1.find方法
auto it=hashTable.find("apple");
//auto:计算机会根据返回的情况确定类型
//找到返回,不等于哈希表的最后一个说明找到了
if(it!=hashTable.end()){
	std::cout<<"Found"<<it->second<<std::endl;
	//it->second为apple键对应的值,std::endl为输出换行
}else{
//找到最后没找到
	std::cout<<"Not found"<<std::endl;
}

//用[]操作符,如果键不存在,返回默认值0
//如果键存在,返回值
int value=hashTable["cherry"];

删除元素

用erase方法删除

clike 复制代码
//删除键为"banana"的元素
hashTable.erase("banana");

遍历哈希表

c 复制代码
for(auto it=hashTable.begin();it!=hashTable.end();++it){
	std::cout<<it->first<<"->"<<it->sceond<<std::endl;
}
//从哈希表的开始到哈希表的结束,每次+1
//it->first为键,it->second为值

count检查是否存在某个键

作用:

  • 如果键存在,返回1
  • 如果键不存在,返回0;
    来找哈希表里是否有特定的键

例:

c 复制代码
//声明哈希表,键的类型为int,值的类型为字符串
std::unordered_map<int,std::string>hashTable;

//插入一些键值对
hashTable[1]="one";
hashTable[2]="two";

//检查键是否存在
if(hashTable.count(1)>0){
//返回1,说明找到了
	std::cout<<"键1在哈希表里有"<<std::endl;
}else{
	std::cout<<"键1不在哈希表里"<<std::endl;
}
相关推荐
clint4563 天前
C++进阶(1)——前景提要
c++
夜悊4 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴4 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0014 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾4 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you4 天前
constexpr函数
c++
凡人叶枫4 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫4 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss4 天前
BRpc使用
c++·rpc
-森屿安年-4 天前
63. 不同路径 II
c++·算法·动态规划