Namespaces
Variants

std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>:: find

From cppreference.net

iterator find ( const Key & key ) ;
(1) (C++23부터)
(C++26부터 constexpr)
const_iterator find ( const Key & key ) const ;
(2) (C++23부터)
(C++26부터 constexpr)
template < class K >
iterator find ( const K & x ) ;
(3) (C++23부터)
(C++26부터 constexpr)
template < class K >
const_iterator find ( const K & x ) const ;
(4) (C++23부터)
(C++26부터 constexpr)
1,2) key 와 동등한 키를 가진 요소를 찾습니다.
3,4) 키가 x 와 동등하게 비교되는 요소를 찾습니다.
이 오버로드는 Compare transparent 인 경우에만 오버로드 해결에 참여합니다. 이를 통해 Key 의 인스턴스를 생성하지 않고 이 함수를 호출할 수 있습니다.

목차

매개변수

key - 검색할 요소의 키 값
x - 키와 투명하게 비교될 수 있는 임의의 타입의 값

반환값

요청된 요소에 대한 반복자. 해당 요소를 찾지 못한 경우, 끝 지난(past-the-end) (참조 end() ) 반복자가 반환됩니다.

복잡도

컨테이너 크기에 대해 로그 시간 복잡도를 가집니다.

예제

#include <iostream>
#include <flat_map>
struct LightKey
{
    int x;
};
struct FatKey
{
    int x;
    int data[1000]; // 무거운 데이터 블롭
};
// 위에서 상세히 설명한 대로, 컨테이너는 이러한 오버로드에 접근하기 위해
// std::less<> (또는 다른 투명 비교자)를 사용해야 합니다. 여기에는
// std::string과 std::string_view 간의 비교와 같은 표준 오버로드가 포함됩니다.
bool operator<(const FatKey& fk, const LightKey& lk) { return fk.x < lk.x; }
bool operator<(const LightKey& lk, const FatKey& fk) { return lk.x < fk.x; }
bool operator<(const FatKey& fk1, const FatKey& fk2) { return fk1.x < fk2.x; }
int main()
{
    // 간단한 비교 데모
    std::flat_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";
    // 투명 비교 데모
    std::flat_map<FatKey, char, std::less<>> example2{{{1, {}}, 'a'}, {{2, {}}, 'b'}};
    LightKey lk = {2};
    if (auto search = example2.find(lk); search != example2.end())
        std::cout << "Found " << search->first.x << ' ' << search->second << '\n';
    else
        std::cout << "Not found\n";
    // const 반복자 획득
    // 컴파일러는 맵에 접근하는 방식에 따라 (비)const 타입의 반복자를 반환할지 결정합니다.
    // 의도적인 수정을 방지하기 위한 가장 간단한 방법 중 하나는
    // 상수 참조를 통해 맵에 접근하는 것입니다.
    const auto& example2ref = example2;
    if (auto search = example2ref.find(lk); search != example2.end())
    {
        std::cout << "Found " << search->first.x << ' ' << search->second << '\n';
    //  search->second = 'c'; // 오류: 읽기 전용 객체에서
                              // 'std::pair<const FatKey, char>::second' 멤버의 할당
    }
}

출력:

Found 2 b
Found 2 b
Found 2 b

참고 항목

경계 검사와 함께 지정된 요소에 접근
(public member function)
지정된 요소에 접근 또는 삽입
(public member function)
특정 키와 일치하는 요소의 수를 반환
(public member function)
특정 키와 일치하는 요소들의 범위를 반환
(public member function)