std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::find
来自 cppreference.cn
< cpp | container | unordered map
iterator find( const Key& key ); |
(1) | (since C++11) |
const_iterator find( const Key& key ) const; |
(2) | (since C++11) |
template< class K > iterator find( const K& x ); |
(3) | (since C++20) |
template< class K > const_iterator find( const K& x ) const; |
(4) | (since C++20) |
1,2) 查找键与 key 等价的元素。
3,4) 查找键与值 x 等价 比较的元素。此重载仅在 Hash::is_transparent 和 KeyEqual::is_transparent 有效且各自表示类型时参与重载决议。这假定此
Hash
可用 K
和 Key
类型调用,并且 KeyEqual
是透明的,这共同允许在不构造 Key
实例的情况下调用此函数。内容 |
[编辑] 参数
key | - | 要搜索的元素的键值 |
x | - | 可以与键透明比较的任何类型的值 |
[编辑] 返回值
指向所请求元素的迭代器。如果未找到此类元素,则返回过尾(参见 end())迭代器。
[编辑] 复杂度
平均为常数时间,最坏情况为容器大小的线性时间。
注意
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_generic_unordered_lookup |
201811L |
(C++20) | 无序关联容器 中的异构比较查找;重载 (3,4) |
[编辑] 示例
运行此代码
#include <cstddef> #include <functional> #include <iostream> #include <string> #include <string_view> #include <unordered_map> using namespace std::literals; struct string_hash { using hash_type = std::hash<std::string_view>; using is_transparent = void; std::size_t operator()(const char* str) const { return hash_type{}(str); } std::size_t operator()(std::string_view str) const { return hash_type{}(str); } std::size_t operator()(std::string const& str) const { return hash_type{}(str); } }; int main() { // simple comparison demo std::unordered_map<int, char> example{{1, 'a'}, {2, 'b'}}; if (auto search = example.find(2); search != example.end()) std::cout << "Found " << search->first << ' ' << search->second << '\n'; else std::cout << "Not found\n"; // C++20 demo: Heterogeneous lookup for unordered containers (transparent hashing) 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
[编辑] 参见
访问带边界检查的指定元素 (公共成员函数) | |
访问或插入指定元素 (公共成员函数) | |
返回匹配特定键的元素数量 (公共成员函数) | |
返回匹配特定键的元素范围 (公共成员函数) |