std::unordered_set<Key,Hash,KeyEqual,Allocator>::find
From cppreference.com
< cpp | container | unordered set
| 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 ( end() ) へのイテレータが返されます。
[編集] 計算量
平均的には定数時間、最悪の場合はコンテナのサイズに線形時間。
注釈
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__cpp_lib_generic_unordered_lookup |
201811L |
(C++20) | unordered associative containers における異種比較ルックアップ。オーバーロード (3,4) |
[編集] 例
このコードを実行
#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
[編集] 関連項目
| 特定のキーに一致する要素の数を返す (公開メンバ関数) | |
| 特定のキーに一致する要素の範囲を返す (公開メンバ関数) |