std::unordered_set<Key,Hash,KeyEqual,Allocator>::find
来自 cppreference.cn
< cpp | container | unordered set
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
实例的情况下调用此函数。目录 |
[edit] 参数
key | - | 要搜索的元素的键值 |
x | - | 任何可以与键透明比较的类型的值 |
[edit] 返回值
指向所请求元素的迭代器。 如果未找到此类元素,则返回过尾(参见 end())迭代器。
[edit] 复杂度
平均为常数时间,最坏情况为容器大小的线性时间。
注解
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_generic_unordered_lookup |
201811L |
(C++20) | 无序关联容器中的异构比较查找;重载 (3,4) |
[edit] 示例
运行此代码
#include <cstddef> #include <functional> #include <iostream> #include <source_location> #include <string> #include <string_view> #include <unordered_set> using namespace std::literals; namespace logger { bool enabled{false}; } inline void who(const std::source_location sloc = std::source_location::current()) { if (logger::enabled) std::cout << sloc.function_name() << '\n'; } struct string_hash // C++20's transparent hashing { using hash_type = std::hash<std::string_view>; using is_transparent = void; std::size_t operator()(const char* str) const { who(); return hash_type{}(str); } std::size_t operator()(std::string_view str) const { who(); return hash_type{}(str); } std::size_t operator()(std::string const& str) const { who(); return hash_type{}(str); } }; int main() { std::unordered_set<int> example{1, 2, -10}; std::cout << "Simple comparison demo:\n" << std::boolalpha; if (auto search = example.find(2); search != example.end()) std::cout << "Found " << *search << '\n'; else std::cout << "Not found\n"; std::unordered_set<std::string, string_hash, std::equal_to<>> set{"one"s, "two"s}; logger::enabled = true; std::cout << "Heterogeneous lookup for unordered containers (transparent hashing):\n" << (set.find("one") != set.end()) << '\n' << (set.find("one"s) != set.end()) << '\n' << (set.find("one"sv) != set.end()) << '\n'; }
可能的输出
Simple comparison demo: Found 2 Heterogeneous lookup for unordered containers (transparent hashing): std::size_t string_hash::operator()(const char*) const true std::size_t string_hash::operator()(const std::string&) const true std::size_t string_hash::operator()(std::string_view) const true
[edit] 参见
返回匹配特定键的元素数量 (公共成员函数) | |
返回匹配特定键的元素范围 (公共成员函数) |