std::unordered_map<Key,T,Hash,KeyEqual,Allocator>:: find
From cppreference.net
<
cpp
|
container
|
unordered map
|
iterator find
(
const
Key
&
key
)
;
|
(1) |
(自 C++11 起)
(自 C++26 起为 constexpr) |
|
const_iterator find
(
const
Key
&
key
)
const
;
|
(2) |
(自 C++11 起)
(自 C++26 起为 constexpr) |
|
template
<
class
K
>
iterator find ( const K & x ) ; |
(3) |
(自 C++20 起)
(自 C++26 起为 constexpr) |
|
template
<
class
K
>
const_iterator find ( const K & x ) const ; |
(4) |
(自 C++20 起)
(自 C++26 起为 constexpr) |
1,2)
查找键值等于
key
的元素。
3,4)
查找键值与
x
等价的元素。
此重载仅当
Hash
与
KeyEqual
均为
透明函数对象
时参与重载决议。该条件要求
Hash
可同时被
K
和
Key
类型调用,且
KeyEqual
具有透明性,二者结合使得无需构造
Key
实例即可调用此函数。
目录 |
参数
| key | - | 要搜索元素的键值 |
| x | - | 可与键进行透明比较的任意类型值 |
返回值
指向所请求元素的迭代器。若找不到该元素,则返回尾后(参见 end() )迭代器。
复杂度
平均情况下为常数时间复杂度,最坏情况下与容器大小呈线性关系。
注释
| 功能测试 宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__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()(const std::string& 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 << "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
参阅
|
访问指定元素(带边界检查)
(公开成员函数) |
|
|
访问或插入指定元素
(公开成员函数) |
|
|
返回匹配特定键的元素数量
(公开成员函数) |
|
|
返回匹配特定键的元素范围
(公开成员函数) |