C++ STL——hash/unordered_set/c++11关键字decltype

本文主要介绍了C++ STL中的hash类模板和unordered_set类模板,包括它们的定义、作用以及如何使用。通过示例代码展示了如何创建和操作unordered_set,并解释了hash函数的作用和find()、equal_range()等方法的功能。同时,文中还探讨了C++11关键字decltype在函数模板中的应用。

摘自MSDN,以VS2012版为主


1、hash类模板

定义如下:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template<class Ty>  
  2.     struct hash  
  3.         : public unary_function<Ty, size_t> {  
  4.     size_t operator()(Ty _Val) const;  
  5.     };  

并给出一个例子:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // std_tr1__functional__hash.cpp   
  2. // compile with: /EHsc   
  3. #include <functional>   
  4. #include <iostream>   
  5. #include <unordered_set>   
  6.    
  7. int main()   
  8.     {   
  9.     std::unordered_set<int, std::hash<int> > c0;   
  10.     c0.insert(3);   
  11.     std::cout << *c0.find(3) << std::endl;   
  12.    
  13.     return (0);   
  14.     }   
  15.    
输出结果3


2.unordered_set类模板

定义:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template<class Key,  
  2.     class Hash = std::hash<Key>,  
  3.     class Pred = std::equal_to<Key>,  
  4.     class Alloc = std::allocator<Key> >  
  5.     class unordered_set;  

Parameters

Parameter

Description

Key

The key type.

Hash

The hash function object type.

Pred

The equality comparison function object type.

Alloc

The allocator class.


结合第一个例子说明一下,
unordered_set是c++11引入的散列容器,在没有冲突的情况下,时间复杂度是常数时间。内部通过hash函数进行弱排序。

在说明unordered_set之前,先说明hash函数。


hash,百度百科中翻译为"散列"或者”哈希“,其通过一个hash函数,建立一个散列表,举个例子:


假设 (员工   工资);   zhao  3550;qian  4600;sun  4300;zhai 5210

设计一个hash函数,姓对应其首字母的ascii码,即zhao(Z)-90,qian(Q)-81,sun(S)-83,zhai(Z)-90

这就是所谓的  h(key)=value,h表示hash函数


这里第一个和第四个冲突,把第四个存在第一个旁边

开辟一个大小为200的数组H,H[90]=3550;H[81]=4600;H[83]=4300;H[91]=5210;

这种做法效率极其低下,但在没有冲突情况下是常数运行时间。


实际中,内存中是这么存储的,separate chaining:



LEN表示这个vec长度,可以看出一个vector,每个vec[i]暂且称为一个node,每个node后面一串叫做buckets,每个buckets是可变大小。



在回过头,讲unordered_set

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. std::unordered_set<int, std::hash<int> > c0;   

 

hash<int>是一个实例化后的函数类

文章开头,

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. size_t operator()(Ty _Val) const;  

实际上是对运算符()重载

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. *c0.find(3)  
相当于

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. *(c0.find(3))  


说明find()之前,需要了解equal_range;

equal_range:返回一个pair,即[X.first, X.second) ,其中X是迭代器,限制了key的范围

[cpp]  view plain  copy
  1. std::pair<iterator, iterator>  
  2.     equal_range(const Key& keyval);  
  3. std::pair<const_iterator, const_iterator>  
  4.     equal_range(const Key& keyval) const;  

[cpp]  view plain  copy
  1. // std_tr1__unordered_set__unordered_set_equal_range.cpp   
  2. // compile with: /EHsc   
  3. #include <unordered_set>   
  4. #include <iostream>   
  5.   
  6. typedef std::unordered_set<char> Myset;   
  7. int main()   
  8.     {   
  9.     Myset c1;   
  10.   
  11.     c1.insert('a');   
  12.     c1.insert('b');   
  13.     c1.insert('c');   
  14.   
  15. // display contents " [c] [b] [a]"   
  16.     for (Myset::const_iterator it = c1.begin();   
  17.         it != c1.end(); ++it)   
  18.         std::cout << " [" << *it << "]";   
  19.     std::cout << std::endl;   
  20.   
  21. // display results of failed search   
  22.     std::pair<Myset::iterator, Myset::iterator> pair1 =   
  23.         c1.equal_range('x');   
  24.     std::cout << "equal_range('x'):";   
  25.     for (; pair1.first != pair1.second; ++pair1.first)   
  26.         std::cout << " [" << *pair1.first << "]";   
  27.     std::cout << std::endl;   
  28.   
  29. // display results of successful search   
  30.     pair1 = c1.equal_range('b');   
  31.     std::cout << "equal_range('b'):";   
  32.     for (; pair1.first != pair1.second; ++pair1.first)   
  33.         std::cout << " [" << *pair1.first << "]";   
  34.     std::cout << std::endl;   
  35.   
  36.     return (0);   
  37.     }   

结果:

[a]  [b]   [c]
equal_range('x'):
equal_range('b'):    [b]


再看一个find的例子

[cpp]  view plain  copy
  1. const_iterator find(const Key& keyval) const;  

find返回 unordered_set::equal_range(keyval).first

[cpp]  view plain  copy
  1. // std_tr1__unordered_set__unordered_set_find.cpp   
  2. // compile with: /EHsc   
  3. #include <unordered_set>   
  4. #include <iostream>   
  5.   
  6. typedef std::unordered_set<char> Myset;   
  7. int main()   
  8. {   
  9.     Myset c1;   
  10.   
  11.     c1.insert('a');   
  12.     c1.insert('b');   
  13.     c1.insert('c');   
  14.   
  15.     // display contents " [c] [b] [a]"   
  16.     // 我用VS2012编译是" [a] [b] [c]"  
  17.     for (Myset::const_iterator it = c1.begin();   
  18.         it != c1.end(); ++it)   
  19.         std::cout << " [" << *it << "]";   
  20.     std::cout << std::endl;   
  21.   
  22.     // try to find and fail   
  23.     std::cout << "find('A') == "   
  24.         << std::boolalpha << (c1.find('A') != c1.end()) << std::endl;   
  25.   
  26.     // try to find and succeed   
  27.     Myset::iterator it = c1.find('b');   
  28.     std::cout << "find('b') == "   
  29.         << std::boolalpha << (it != c1.end())   
  30.         << ": [" << *it << "]" << std::endl;   
  31.   
  32.     return (0);   
  33. }   


结果:

[a]  [b]  [c]

find('A')==false

find('b')==true: [b]

要注意的是:

[cpp]  view plain  copy
  1. c1.end()  
不指向最后一个元素,而指向最后一个元素再+1,当find不到输入的元素时候,返回迭代器就指向这个end()



更复杂的代码分析:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>   
  2. #include <unordered_set>  
  3.   
  4.   
  5.   
  6.   
  7. using namespace std;  
  8.   
  9.   
  10. size_t hash_function_pair_int(pair<intint> p)  
  11. {  
  12. return hash<int>()(p.first - p.second);  
  13. }  
  14.   
  15.   
  16. typedef  unordered_set < pair<intint>, decltype(hash_function_pair_int)* > set_pair_int;  
  17.   
  18.   
  19. void main()  
  20. {  
  21. set_pair_int boundEdge(10,hash_function_pair_int);  
  22.   
  23.   
  24. pair<int,int> f0(4,3),f1(3,1),f2(3,2),f3(3,2);  
  25. boundEdge.insert(f0);  
  26. boundEdge.insert(f1);  
  27. boundEdge.insert(f2);  
  28. boundEdge.insert(f3);  
  29. }  

关键字decltype自动推断表达式类型;

hash<int>()是一个匿名对象,

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. hash<int>()(p.first - p.second)  

后面第二个()是操作符重载,输入参数是pair的first和second的差

In file included from D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/bits/hashtable_policy.h:34, from D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/bits/hashtable.h:35, from D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/bits/unordered_map.h:33, from D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/unordered_map:41, from D:/obj/i wanna own world to me/i wanna own world to me.cpp:9: D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/tuple: In instantiation of 'constexpr std::pair<_T1, _T2>::pair(std::tuple<_Args1 ...>&, std::tuple<_Args2 ...>&, std::_Index_tuple<_Indexes1 ...>, std::_Index_tuple<_Indexes2 ...>) [with _Args1 = {std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&}; long long unsigned int ..._Indexes1 = {0}; _Args2 = {}; long long unsigned int ..._Indexes2 = {}; _T1 = const std::__cxx11::basic_string<char>; _T2 = SDL_GL_Image]': D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/tuple:2877:63: required from 'constexpr std::pair<_T1, _T2>::pair(std::piecewise_construct_t, std::tuple<_Args1 ...>, std::tuple<_Args2 ...>) [with _Args1 = {std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&}; _Args2 = {}; _T1 = const std::__cxx11::basic_string<char>; _T2 = SDL_GL_Image]' 2877 | typename _Build_index_tuple<sizeof...(_Args2)>::__type()) | ^ D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/bits/stl_construct.h:97:14: required from 'constexpr decltype (::new(void*(0)) _Tp) std::construct_at(_Tp*, _Args&& ...) [with _Tp = pair<const __cxx11::basic_string<char>, SDL_GL_Image>; _Args = {const piecewise_construct_t&, tuple<__cxx11::basic_string<char, char_traits<char>, allocator<char> >&&>, tuple<>}; decltype (::new(void*(0)) _Tp) = pair<const __cxx11::basic_string<char>, SDL_GL_Image>*]' 97 | { return ::new((void*)__location) _Tp(std::forward<_Args>(__args)...); } | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/bits/alloc_traits.h:536:21: required from 'static constexpr void std::allocator_traits<std::allocator<_Up> >::construct(allocator_type&, _Up*, _Args&& ...) [with _Up = std::pair<const std::__cxx11::basic_string<char>, SDL_GL_Image>; _Args = {const std::piecewise_construct_t&, std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&>, std::tuple<>}; _Tp = std::__detail::_Hash_node<std::pair<const std::__cxx11::basic_string<char>, SDL_GL_Image>, true>; allocator_type = std::allocator<std::__detail::_Hash_node<std::pair<const std::__cxx11::basic_string<char>, SDL_GL_Image>, true> >]' 536 | std::construct_at(__p, std::forward<_Args>(__args)...); | ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/bits/hashtable_policy.h:2024:36: required from 'std::__detail::_Hashtable_alloc<_NodeAlloc>::__node_type* std::__detail::_Hashtable_alloc<_NodeAlloc>::_M_allocate_node(_Args&& ...) [with _Args = {const std::piecewise_construct_t&, std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&>, std::tuple<>}; _NodeAlloc = std::allocator<std::__detail::_Hash_node<std::pair<const std::__cxx11::basic_string<char>, SDL_GL_Image>, true> >; __node_ptr = std::allocator<std::__detail::_Hash_node<std::pair<const std::__cxx11::basic_string<char>, SDL_GL_Image>, true> >::value_type*]' 2024 | __node_alloc_traits::construct(__alloc, __n->_M_valptr(), | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~ 2025 | std::forward<_Args>(__args)...); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/bits/hashtable.h:312:35: required from 'std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _Hash, _RangeHash, _Unused, _RehashPolicy, _Traits>::_Scoped_node::_Scoped_node(std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _Hash, _RangeHash, _Unused, _RehashPolicy, _Traits>::__hashtable_alloc*, _Args&& ...) [with _Args = {const std::piecewise_construct_t&, std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&>, std::tuple<>}; _Key = std::__cxx11::basic_string<char>; _Value = std::pair<const std::__cxx11::basic_string<char>, SDL_GL_Image>; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, SDL_GL_Image> >; _ExtractKey = std::__detail::_Select1st; _Equal = std::equal_to<std::__cxx11::basic_string<char> >; _Hash = std::hash<std::__cxx11::basic_string<char> >; _RangeHash = std::__detail::_Mod_range_hashing; _Unused = std::__detail::_Default_ranged_hash; _RehashPolicy = std::__detail::_Prime_rehash_policy; _Traits = std::__detail::_Hashtable_traits<true, false, true>; std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _Hash, _RangeHash, _Unused, _RehashPolicy, _Traits>::__hashtable_alloc = std::_Hashtable<std::__cxx11::basic_string<char>, std::pair<const std::__cxx11::basic_string<char>, SDL_GL_Image>, std::allocator<std::pair<const std::__cxx11::basic_string<char>, SDL_GL_Image> >, std::__detail::_Select1st, std::equal_to<std::__cxx11::basic_string<char> >, std::hash<std::__cxx11::basic_string<char> >, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<true, false, true> >::__hashtable_alloc]' 312 | _M_node(__h->_M_allocate_node(std::forward<_Args>(__args)...)) | ~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/bits/hashtable_policy.h:870:42: required from 'std::__detail::_Map_base<_Key, std::pair<const _Key, _Val>, _Alloc, std::__detail::_Select1st, _Equal, _Hash, _RangeHash, _Unused, _RehashPolicy, _Traits, true>::mapped_type& std::__detail::_Map_base<_Key, std::pair<const _Key, _Val>, _Alloc, std::__detail::_Select1st, _Equal, _Hash, _RangeHash, _Unused, _RehashPolicy, _Traits, true>::operator[](key_type&&) [with _Key = std::__cxx11::basic_string<char>; _Val = SDL_GL_Image; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, SDL_GL_Image> >; _Equal = std::equal_to<std::__cxx11::basic_string<char> >; _Hash = std::hash<std::__cxx11::basic_string<char> >; _RangeHash = std::__detail::_Mod_range_hashing; _Unused = std::__detail::_Default_ranged_hash; _RehashPolicy = std::__detail::_Prime_rehash_policy; _Traits = std::__detail::_Hashtable_traits<true, false, true>; mapped_type = SDL_GL_Image; key_type = std::__cxx11::basic_string<char>]' 870 | typename __hashtable::_Scoped_node __node { | ^~~~~~ D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/bits/unordered_map.h:992:20: required from 'std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::mapped_type& std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::operator[](key_type&&) [with _Key = std::__cxx11::basic_string<char>; _Tp = SDL_GL_Image; _Hash = std::hash<std::__cxx11::basic_string<char> >; _Pred = std::equal_to<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, SDL_GL_Image> >; mapped_type = SDL_GL_Image; key_type = std::__cxx11::basic_string<char>]' 992 | { return _M_h[std::move(__k)]; } | ~~~~^ D:/obj/i wanna own world to me/i wanna own world to me.cpp:164:57: required from here 164 | glBindTexture(GL_TEXTURE_2D, images["sprBrownBlock"s].textureID); | ^ D:/SelfUsing/Language/CLion 2025.1.3/mingw/lib/gcc/x86_64-w64-mingw32/14.2.0/include/c++/tuple:2888:9: error: no matching function for call to 'SDL_GL_Image::SDL_GL_Image()' 2888 | second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...) | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ D:/obj/i wanna own world to me/i wanna own world to me.cpp:43:14: note: candidate: 'SDL_GL_Image::SDL_GL_Image(const char*)' 43 | explicit SDL_GL_Image(const char* path) { | ^~~~~~~~~~~~ D:/obj/i wanna own world to me/i wanna own world to me.cpp:43:14: note: candidate expects 1 argument, 0 provided D:/obj/i wanna own world to me/i wanna own world to me.cpp:39:7: note: candidate: 'constexpr SDL_GL_Image::SDL_GL_Image(const SDL_GL_Image&)' 39 | union SDL_GL_Image { | ^~~~~~~~~~~~ D:/obj/i wanna own world to me/i wanna own world to me.cpp:39:7: note: candidate expects 1 argument, 0 provided ninja: build stopped: subcommand failed.
08-05
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值