std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::find
來自 cppreference.com
| iterator find( const Key& key ); |
(1) | (C++11 起) |
| const_iterator find( const Key& key ) const; |
(2) | (C++11 起) |
template< class K > iterator find( const K& x ); |
(3) | (C++20 起) |
template< class K > const_iterator find( const K& x ) const; |
(4) | (C++20 起) |
1,2) 查詢鍵等價於 key 的元素。
3,4) 查詢鍵與值 x 等價的元素。此過載僅當 Hash::is_transparent 和 KeyEqual::is_transparent 有效且均表示型別時才參與過載決議。這假定此類
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()(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
[編輯] 參閱
| 訪問指定的元素,帶邊界檢查 (public member function) | |
| 訪問或插入指定元素 (public member function) | |
| 返回匹配特定鍵的元素數量 (public member function) | |
| 返回與特定鍵匹配的元素範圍 (public member function) |