Namespaces
Variants

std::unordered_set<Key,Hash,KeyEqual,Allocator>:: find

From cppreference.net

iterator find ( const Key & key ) ;
(1) (начиная с C++11)
(constexpr начиная с C++26)
const_iterator find ( const Key & key ) const ;
(2) (начиная с C++11)
(constexpr начиная с C++26)
template < class K >
iterator find ( const K & x ) ;
(3) (начиная с C++20)
(constexpr начиная с C++26)
template < class K >
const_iterator find ( const K & x ) const ;
(4) (начиная с C++20)
(constexpr начиная с C++26)
1,2) Находит элемент с ключом, эквивалентным key .
3,4) Находит элемент с ключом, эквивалентным x .
Эта перегрузка участвует в разрешении перегрузки только если Hash и KeyEqual оба являются прозрачными . Это предполагает, что такой 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 <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()(const std::string& 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

Смотрите также

возвращает количество элементов, соответствующих определённому ключу
(public member function)
возвращает диапазон элементов, соответствующих определённому ключу
(public member function)