Namespaces
Variants

std::ranges:: equal_range

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
헤더 파일에 정의됨 <algorithm>
호출 시그니처
(1)
template < std:: forward_iterator I, std:: sentinel_for < I > S,

class T, class Proj = std:: identity ,
std:: indirect_strict_weak_order
< const T * , std :: projected < I, Proj >> Comp = ranges:: less >
constexpr ranges:: subrange < I > equal_range ( I first, S last, const T & value,

Comp comp = { } , Proj proj = { } ) ;
(C++20부터)
(C++26까지)
template < std:: forward_iterator I, std:: sentinel_for < I > S,

class Proj = std:: identity ,
class T = std :: projected_value_t < I, Proj > ,
std:: indirect_strict_weak_order
< const T * , std :: projected < I, Proj >> Comp = ranges:: less >
constexpr ranges:: subrange < I > equal_range ( I first, S last, const T & value,

Comp comp = { } , Proj proj = { } ) ;
(C++26부터)
(2)
template < ranges:: forward_range R,

class T, class Proj = std:: identity ,
std:: indirect_strict_weak_order
< const T * , std :: projected < ranges:: iterator_t < R > ,
Proj >> Comp = ranges:: less >
constexpr ranges:: borrowed_subrange_t < R >

equal_range ( R && r, const T & value, Comp comp = { } , Proj proj = { } ) ;
(C++20부터)
(C++26까지)
template < ranges:: forward_range R,

class Proj = std:: identity ,
class T = std :: projected_value_t < ranges:: iterator_t < R > , Proj > ,
std:: indirect_strict_weak_order
< const T * , std :: projected < ranges:: iterator_t < R > ,
Proj >> Comp = ranges:: less >
constexpr ranges:: borrowed_subrange_t < R >

equal_range ( R && r, const T & value, Comp comp = { } , Proj proj = { } ) ;
(C++26부터)
1) 범위 [ first , last ) 에서 value 와 동등한 모든 요소를 포함하는 뷰를 반환합니다.

범위 [ first , last ) value 에 대해 최소한 부분적으로 정렬되어야 합니다, 즉 다음 요구 사항을 모두 충족해야 합니다:

  • element < value 또는 comp ( element, value ) 에 대해 분할됨 (즉, 표현식이 true 인 모든 요소가 표현식이 false 인 모든 요소 앞에 옴).
  • ! ( value < element ) 또는 ! comp ( value, element ) 에 대해 분할됨.
  • 모든 요소에 대해, element < value 또는 comp ( element, value ) true 이면 ! ( value < element ) 또는 ! comp ( value, element ) true 임.

완전히 정렬된 범위는 다음 기준을 충족합니다.

반환된 뷰는 두 개의 반복자로 구성되며, 하나는 value 보다 작지 않은 첫 번째 요소를 가리키고, 다른 하나는 value 보다 첫 번째 요소를 가리킵니다. 첫 번째 반복자는 std::ranges::lower_bound() 로, 두 번째 반복자는 std::ranges::upper_bound() 로 각각 얻을 수 있습니다.

2) (1) 과 동일하지만, r 를 소스 범위로 사용하며, 마치 범위 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

목차

매개변수

first, last - 검사할 요소들의 범위 를 정의하는 반복자-감시자 쌍
r - 검사할 요소들의 범위
value - 요소들과 비교할 값
comp - 첫 번째 인수가 두 번째 인수보다 작은지 (즉, 순서상 앞서는지) 여부
proj - 요소들에 적용할 투영(projection)

반환값

std::ranges::subrange 원하는 범위를 정의하는 한 쌍의 반복자를 포함하며, 첫 번째는 value 보다 작지 않은 첫 번째 요소를 가리키고, 두 번째는 value 보다 첫 번째 요소를 가리킵니다.

value 이상인 요소가 없는 경우, 마지막 반복자( last 와 동일한 반복자 또는 ranges:: end ( r ) )가 첫 번째 요소로 반환됩니다. 마찬가지로 value 보다 큰 요소가 없는 경우, 마지막 반복자가 두 번째 요소로 반환됩니다.

복잡도

비교 수행 횟수는 first last 사이의 거리에 대해 로그적입니다 (최대 2 * log 2 (last - first) + O(1) 번의 비교). 그러나 random_access_iterator 를 모델링하지 않는 반복자의 경우, 반복자 증감 횟수는 선형입니다.

가능한 구현

struct equal_range_fn
{
    template<std::forward_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity, class T = std::projected_value_t<I, Proj>,
             std::indirect_strict_weak_order
                 <const T*, std::projected<I, Proj>> Comp = ranges::less>
    constexpr ranges::subrange<I>
        operator()(I first, S last, const T& value, Comp comp = {}, Proj proj = {}) const
    {
        return ranges::subrange
        (
            ranges::lower_bound(first, last, value, std::ref(comp), std::ref(proj)),
            ranges::upper_bound(first, last, value, std::ref(comp), std::ref(proj))
        );
    }
    template<ranges::forward_range R, class Proj = std::identity,
             class T = std::projected_value_t<ranges::iterator_t<R>, Proj>,
             std::indirect_strict_weak_order
                 <const T*, std::projected<ranges::iterator_t<R>,
                                           Proj>> Comp = ranges::less>
    constexpr ranges::borrowed_subrange_t<R>
        operator()(R&& r, const T& value, Comp comp = {}, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), value,
                       std::ref(comp), std::ref(proj));
    }
};
inline constexpr equal_range_fn equal_range;

참고 사항

기능 테스트 매크로 표준 기능
__cpp_lib_algorithm_default_value_type 202403 (C++26) 목록 초기화 for algorithms ( 1,2 )

예제

#include <algorithm>
#include <compare>
#include <complex>
#include <iostream>
#include <vector>
struct S
{
    int number {};
    char name {};
    // 참고: name은 이 비교 연산자들에서 무시됨
    friend bool operator== (const S s1, const S s2) { return s1.number == s2.number; }
    friend auto operator<=>(const S s1, const S s2) { return s1.number <=> s2.number; }
    friend std::ostream& operator<<(std::ostream& os, S o)
    {
        return os << '{' << o.number << ", '" << o.name << "'}";
    }
};
void println(auto rem, const auto& v)
{
    for (std::cout << rem; const auto& e : v)
        std::cout << e << ' ';
    std::cout << '\n';
}
int main()
{
    // 참고: 정렬되지 않음, 아래 정의된 S에 대해 분할만 됨
    std::vector<S> vec
    {
        {1,'A'}, {2,'B'}, {2,'C'}, {2,'D'}, {4, 'D'}, {4,'G'}, {3,'F'}
    };
    const S value{2, '?'};
    namespace ranges = std::ranges;
    auto a = ranges::equal_range(vec, value);
    println("1. ", a);
    auto b = ranges::equal_range(vec.begin(), vec.end(), value);
    println("2. ", b);
    auto c = ranges::equal_range(vec, 'D', ranges::less {}, &S::name);
    println("3. ", c);
    auto d = ranges::equal_range(vec.begin(), vec.end(), 'D', ranges::less {}, &S::name);
    println("4. ", d);
    using CD = std::complex<double>;
    std::vector<CD> nums{{1, 0}, {2, 2}, {2, 1}, {3, 0}, {3, 1}};
    auto cmpz = [](CD x, CD y) { return x.real() < y.real(); };
    #ifdef __cpp_lib_algorithm_default_value_type
        auto p3 = ranges::equal_range(nums, {2, 0}, cmpz);
    #else
        auto p3 = ranges::equal_range(nums, CD{2, 0}, cmpz);
    #endif
    println("5. ", p3);
}

출력:

1. {2, 'B'} {2, 'C'} {2, 'D'}
2. {2, 'B'} {2, 'C'} {2, 'D'}
3. {2, 'D'} {4, 'D'}
4. {2, 'D'} {4, 'D'}
5. (2,2) (2,1)

참고 항목

주어진 값보다 작지 않은 첫 번째 요소에 대한 반복자를 반환합니다
(알고리즘 함수 객체)
특정 값보다 첫 번째 요소에 대한 반복자를 반환합니다
(알고리즘 함수 객체)
부분적으로 정렬된 범위에 요소가 존재하는지 확인합니다
(알고리즘 함수 객체)
요소들의 범위를 두 그룹으로 분할합니다
(알고리즘 함수 객체)
두 요소 집합이 동일한지 확인합니다
(알고리즘 함수 객체)
특정 키와 일치하는 요소들의 범위를 반환합니다
(함수 템플릿)