std::unordered_map 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 <cstddef>
#include <iostream>
#include <functional>
#include <string>
#include <string_view>
#include <unordered_map>
using namespace std::literals;
using std::size_t;
struct string_hash
{
using hash_type = std::hash<std::string_view>;
using is_transparent = void;
size_t operator()(const char* str) const { return hash_type{}(str); }
size_t operator()(std::string_view str) const { return hash_type{}(str); }
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'}};
auto search = example.find(2);
if (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