std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::find
From 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) | unordered associative containers における異種比較ルックアップ。オーバーロード (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 メンバ関数) | |
| 指定された要素にアクセスまたは挿入する (public メンバ関数) | |
| 特定のキーに一致する要素の数を返す (公開メンバ関数) | |
| 特定のキーに一致する要素の範囲を返す (公開メンバ関数) |