C++中hash map的用法

本文介绍了C++ STL中unordered_map的应用实例,通过具体的代码演示了如何使用基于哈希结构的unordered_map来存储和检索键值对,特别是在大规模数据集上的优势。
部署运行你感兴趣的模型镜像



大家都知道c++ stl中的map是用红黑树实现的,而tr1中实现了hash结构的map 为了不命名冲突被叫做了unordered_map,,

下面就给大家简单使用下这一结构,如果大家的结构在百万规模级就应该考虑使用该结构了。

#include <iostream>
#include <string>
#include <algorithm>
#include <unordered_map>
using namespace std;

void print(std::pair<int,std::string> it)
{
	cout << it.first << "-> " << it.second << endl;
}

void print2(std::pair<string,std::string> it)
{
	cout << it.first << "-> " << it.second << endl;
}


int main(int argc, char* argv[])
{
	typedef std::tr1::unordered_map<int,string> hash_map;
	hash_map hm;
	hm.insert(std::pair<int,std::string>(0,"Hello"));
	hm[1] = "World";
	for_each(hm.begin(),hm.end(),print);


	std::tr1::unordered_map<string,string> hashcode_string;
	hashcode_string.insert(std::pair<string,std::string>("opensss","release"));

	hashcode_string["opensde"] = "ssss";
	for_each(hashcode_string.begin(),hashcode_string.end(),print2);

	system("pause");
	return 0;
}


您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

### C++ 中 `hash_map` 的用法与实现 #### 关于 `hash_map` 在标准模板库(STL)中,C++ 提供了一种基于哈希表的数据结构——`unordered_map`,它实际上就是 `hash_map` 的标准化版本[^1]。尽管早期的某些编译器可能支持 `hash_map` 作为扩展功能,但在现代 C++ 标准中,推荐使用 `std::unordered_map` 来替代。 以下是关于 `std::unordered_map` 的基本介绍及其常见用途: #### 基本定义 `std::unordered_map` 是一种关联容器,用于存储键值对,并通过哈希函数快速访问数据。它的主要特点是平均时间复杂度为 O(1),适用于查找、插入和删除操作频繁的应用场景[^2]。 #### 使用示例 下面是一个简单的例子展示如何创建并操作 `std::unordered_map`: ```cpp #include <iostream> #include <unordered_map> int main() { std::unordered_map<std::string, int> word_count; // 插入元素 word_count["apple"] = 1; word_count["banana"] += 1; // 查找元素 if (word_count.find("apple") != word_count.end()) { std::cout << "Found apple with count: " << word_count["apple"] << '\n'; } // 遍历所有元素 for (const auto& pair : word_count) { std::cout << pair.first << ": " << pair.second << '\n'; } } ``` 此代码片段展示了如何向 `unordered_map` 添加新条目以及检索现有条目的过程[^3]。 #### 性能考量 虽然 `std::unordered_map` 能够提供高效的查询性能,但它依赖于良好的哈希函数设计来减少冲突的发生率。如果发生大量碰撞,则可能导致退化到接近线性的表现。因此,在实际应用时需注意选择合适的键类型及自定义哈希函数。 #### 自定义哈希函数 当默认提供的哈希机制无法满足需求时,可以为特定类型的键指定自己的哈希算法。例如对于用户定义类对象作为 key 的情况: ```cpp struct Point { int x, y; }; namespace std { template <> struct hash<Point> { size_t operator()(Point const& p) const noexcept { return hash<int>()(p.x) ^ (hash<int>()(p.y) << 1); } }; } void exampleUsage() { unordered_map<Point, string> points_to_names; points_to_names[{1, 2}] = "point_one"; } ``` 上述代码实现了针对 `Point` 类型的一个简单哈希计算逻辑。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值