std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::find

来自cppreference.com
 
 
 
 
iterator find(const Key& key );
(1) (C++11 起)
const_iterator find(const Key& key )const;
(2) (C++11 起)
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_transparentKeyEqual::is_transparent 均合法并指代类型时才会参与重载决议。这假设使得 Hash 能用 KKey 类型调用,并且 KeyEqual 是透明的,进而允许调用此函数时不需要构造 Key 的实例。

目录

[编辑]参数

key - 要搜索的元素键值
x - 能透明地与键比较的任何类型值

[编辑]返回值

指向所需元素的迭代器。若找不到这种元素,则返回尾后(见 end())迭代器。

[编辑]复杂度

平均为常数,最坏情况与容器大小成线性。

注解

功能特性测试标准功能特性
__cpp_lib_generic_unordered_lookup201811L(C++20)无序关联容器中的异质比较查找; 重载 (3,4)

[编辑]示例

#include <cstddef>#include <functional>#include <iostream>#include <string>#include <string_view>#include <unordered_map>   usingnamespace std::literals;   struct string_hash {using hash_type =std::hash<std::string_view>;using is_transparent =void;   std::size_t operator()(constchar* str)const{return hash_type{}(str);}std::size_t operator()(std::string_view str)const{return hash_type{}(str);}std::size_t operator()(std::stringconst& str)const{return hash_type{}(str);}};   int main(){// 简单比较演示std::unordered_map<int, char> example{{1, 'a'}, {2, 'b'}};   if(auto search = example.find(2); search != example.end())std::cout<<"找到了 "<< search->first <<' '<< search->second <<'\n';elsestd::cout<<"未找到\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';}

输出:

找到了 2 b true true true

[编辑]参阅

带越界检查访问指定的元素
(公开成员函数)[编辑]
访问或插入指定的元素
(公开成员函数)[编辑]
返回匹配特定键的元素数量
(公开成员函数)[编辑]
返回匹配特定键的元素范围
(公开成员函数)[编辑]
close