c++ hash_map用法总结

本文总结了C++ STL库中的hash_map使用方法,包括find()和insert()的使用,强调了头文件引用、键值对插入、查找返回值及获取value的注意事项。还提到了使用string作为key时可能出现的编译错误及其解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++ STL库里有自定义的hash_map 方法,但是使用起来并不是那么方便

hash_map主要的方法有

find(),insert()

我结合官方API说明一下他们的用法


一、需要特别注意的地方,

1.头文件的引用

2.如何插入一个<key,value>键值对(参考一下代码)

3.find()的返回值

4.如何获取某一个key值相应的value值

 hm1_RcIter -> second
分别用。first,和,second,指代key和value的值

// hash_map_find.cpp
// compile with: /EHsc
#define _DEFINE_DEPRECATED_HASH_CLASSES 0
#include <hash_map>
#include <iostream>

int main( )
{
   using namespace std;
   using namespace stdext;
   hash_map <int, int> hm1;
   hash_map <int, int> :: const_iterator hm1_AcIter, hm1_RcIter;
   typedef pair <int, int> Int_Pair;

   hm1.insert ( Int_Pair ( 1, 10 ) );
   hm1.insert ( Int_Pair ( 2, 20 ) );
   hm1.insert ( Int_Pair ( 3, 30 ) );

   hm1_RcIter = hm1.find( 2 );
   cout << "The element of hash_map hm1 with a key of 2 is: "
        << hm1_RcIter -> second << "." << endl;

   // If no match is found for the key, end( ) is returned
   hm1_RcIter = hm1.find( 4 );

   if ( hm1_RcIter == hm1.end( ) )
      cout << "The hash_map hm1 doesn't have an element "
           << "with a key of 4." << endl;
   else
      cout << "The element of hash_map hm1 with a key of 4 is: "
           << hm1_RcIter -> second << "." << endl;

   // The element at a specific location in the hash_map can be found 
   // using a dereferenced iterator addressing the location
   hm1_AcIter = hm1.end( );
   hm1_AcIter--;
   hm1_RcIter = hm1.find( hm1_AcIter -> first );
   cout << "The element of hm1 with a key matching "
        << "that of the last element is: "
        << hm1_RcIter -> second << "." << endl;
}
Output
The element of hash_map hm1 with a key of 2 is: 20.
The hash_map hm1 doesn't have an element with a key of 4.
The element of hm1 with a key matching that of the last element is: 30.

二、hash_map使用string和long long做key的问题

当hash_map中使用string为key时,需用户扩展命名空间,否则报错如下:

/usr/lib/gcc/x86_64-redhat-linux/3.4.5/../../../../include/c++/3.4.5/ext/hashtable.h:518: error: no match for call to `(const __gnu_cxx::hash<std::string>) (const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)'
表明编译器错误

解决方法:

#include <ext/hash_map>
namespace __gnu_cxx
{
    template<> struct hash< std::string >
    {
        size_t operator()( const std::string& x ) const
        {
            return hash< const char* >()( x.c_str() );
        }
    };

    template<> struct hash<long long>
    {
        size_t operator()(long long x) const
        {
            return x;
        }
    };
}
### 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` 类型的一个简单哈希计算逻辑。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值