std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::find
来自cppreference.com
                    
                                        
                    < cpp | container | unordered map
                    
                                                            
                    
|   iterator find( const Key& key );  | 
(1) | |
|   const_iterator find( const Key& key ) const;  | 
(2) | |
|   template< class K > iterator find( const K& x );  | 
(3) | (C++20 起) | 
|   template< class K > const_iterator find( const K& x ) const;  | 
(4) | (C++20 起) | 
1,2) 寻找键等于 
key 的的元素。 3,4) 寻找键比较等价于值 
x 的元素。此重载只有在有限定标识 Hash::is_transparent 与 KeyEqual::is_transparent 均合法并指代类型时才会参与重载决议。这假设能用 K 和 Key 类型一起调用这种 Hash ,还有 KeyEqual 是通透的,进而允许不用构造 Key 的实例就调用此函数。参数
| key | - | 要搜索的元素键值 | 
| x | - | 能通透地与键比较的任何类型值 | 
返回值
指向键等于 key 的元素的迭代器。若找不到这种元素,则返回尾后(见 end() )迭代器。
复杂度
平均为常数,最坏情况与容器大小成线性。
示例
运行此代码
#include <cstddef> #include <iostream> #include <functional> #include <string> #include <string_view> #include <unordered_map> using namespace std::literals; using std::size_t; struct string_hash { using hash_type = std::hash<std::string_view>; using is_transparent = void; size_t operator()(const char* str) const { return hash_type{}(str); } size_t operator()(std::string_view str) const { return hash_type{}(str); } size_t operator()(std::string const& str) const { return hash_type{}(str); } }; int main() { // 简单比较演示 std::unordered_map<int,char> example = {{1,'a'},{2,'b'}}; auto search = example.find(2); if (search != example.end()) { std::cout << "Found " << search->first << " " << search->second << '\n'; } else { std::cout << "Not found\n"; } // C++20 演示:无序容器的异质查找(通透哈希) std::unordered_map<std::string, size_t, string_hash, std::equal_to<>> map{ {"one"s, 1} }; std::cout << std::boolalpha << (map.find("one") != map.end()) << '\n' << (map.find("one"s) != map.end()) << '\n' << (map.find("one"sv) != map.end()) << '\n'; }
输出:
Found 2 b true true true
参阅
|    (C++11)  | 
   返回匹配特定键的元素数量   (公开成员函数)  | 
|    (C++11)  | 
   返回匹配特定键的元素范围   (公开成员函数)  |