Post

C++哈希表

C++哈希表

基本类型和函数

set和unordered_set

插入元素:insert("apple") 查找元素:find("banana"),找到返回对应位置的迭代器,未找到返回end()迭代器。常用语句:if (mySet.find("banana") != mySet.end()){...}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	#include <unordered_set>
	// 使用 unordered_set
	std::unordered_set<std::string> mySet;
	mySet.insert("apple");
	mySet.insert("banana");
	mySet.insert("orange");
	
	std::cout << "Contents of unordered_set:" << std::endl;
	for (const auto& fruit : mySet){
		std::cout << fruit << std::endl;
	}
	
	// 检查是否包含某个元素
	if (mySet.find("banana") != mySet.end()){
		std::cout << "Set contains banana." << std::endl;
	}

map和unordered_map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	// 使用 unordered_map 
	std::unordered_map<std::string, int> myMap;
	myMap["apple"] = 1;
	myMap["banana"] = 2;
	myMap["orange"] = 3;
	// 查找
	if(hmap.find(2) != hmap.end()){
		cout << iter->second;
	}
	std::cout << "Contents of unordered_map:" << std::endl;
	for (const auto& pair : myMap) {
		std::cout << pair.first << ": " << pair.second << std::endl;
	}
	// 访问某个键对应的值
	std::cout << "Value for 'banana': " << myMap["banana"] << std::endl;

哈希表的相同判定

  • 对于基本数据类型,如 int 和 float,比较通常是基于值的,而不是内存地址。
  • 默认情况下,C++ 中两个struct结构体实例是通过内存地址比较的,因此哈希值相同的条件不成立。为了根据成员变量的值来判断相等性,必须自定义哈希函数。
This post is licensed under CC BY 4.0 by the author.