std::unordered_set find() 方法
- 自 C++20 起
- 自 C++11 起
// (1) Non const version
iterator find( const Key& key );
// (2) Const version
const_iterator find( const Key& key ) const;
// (3) Non const version
template< class K >
iterator find( const K& x );
// (4) Const version
template< class K >
const_iterator find( const K& x ) const;
// (1) Non const version
iterator find( const Key& key );
// (2) Const version
const_iterator find( const Key& key ) const;
- (1-2) 查找键等同于
key
的元素。 - (3-4) 查找键与值
x
比较等效的元素。此重载仅在Hash::is_transparent
和KeyEqual::is_transparent
有效且各自表示一个类型时才参与重载解析。这假定此类Hash
可以与K
和Key
类型一起调用,并且KeyEqual
是透明的,这使得无需构造Key
的实例即可调用此函数。
参数
key
- 要计数的元素的键值x
- 可以与键透明比较的任何类型的值
返回值
指向键与 key
等效的元素的迭代器。如果找不到此类元素,则返回 past-the-end (参阅 end()
) 迭代器。
复杂度
平均情况,常数 - O(1)。
最坏情况下,与容器的大小呈线性关系 - O(size())。
异常
(无)
备注
特性测试宏:__cpp_lib_generic_unordered_lookup
(用于重载 (3-4))。
示例
Main.cpp
#include <unordered_set>
#include <iostream>
int main()
{
// simple comparison demo
std::unordered_set<int> example = {1, 2, 3, 4};
auto search = example.find(2);
if (search != example.end()) {
std::cout << "Found " << (*search) << '\n';
} else {
std::cout << "Not found\n";
}
}
可能输出
Found 2 b