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;
}
相关推荐
端平入洛14 小时前
auto有时不auto
c++
哇哈哈20211 天前
信号量和信号
linux·c++
多恩Stone1 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马2 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝2 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc2 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼2 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛
yyjtx2 天前
DHU上机打卡D31
开发语言·c++·算法
czxyvX2 天前
020-C++之unordered容器
数据结构·c++
会编程的土豆2 天前
2.25 做题
数据结构·c++·算法