Namespaces
Variants

std:: lower_bound

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)
lower_bound
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
헤더 파일에 정의됨 <algorithm>
(1)
template < class ForwardIt, class T >

ForwardIt lower_bound ( ForwardIt first, ForwardIt last,

const T & value ) ;
(C++20부터 constexpr)
(C++26까지)
template < class ForwardIt, class T = typename std:: iterator_traits

< ForwardIt > :: value_type >
constexpr ForwardIt lower_bound ( ForwardIt first, ForwardIt last,

const T & value ) ;
(C++26부터)
(2)
template < class ForwardIt, class T, class Compare >

ForwardIt lower_bound ( ForwardIt first, ForwardIt last,

const T & value, Compare comp ) ;
(C++20부터 constexpr)
(C++26까지)
template < class ForwardIt, class T = typename std:: iterator_traits

< ForwardIt > :: value_type ,
class Compare >
constexpr ForwardIt lower_bound ( ForwardIt first, ForwardIt last,

const T & value, Compare comp ) ;
(C++26부터)

분할된 범위 [ first , last ) 에서 value 보다 먼저 정렬되지 않은 첫 번째 요소를 검색합니다.

1) 순서는 operator < 에 의해 결정됩니다:

[ first , last ) 범위에서 bool ( * iter < value ) false 인 첫 번째 반복자 iter 를 반환합니다. 그러한 iter 가 존재하지 않으면 last 를 반환합니다.

[ first , last ) 범위의 요소들 elem 이 표현식 bool ( elem < value ) 에 대해 분할되어 있지 않으면 , 동작은 정의되지 않습니다.

(C++20 이전)

std :: lower_bound ( first, last, value, std:: less { } ) 와 동등합니다.

(C++20 이후)
2) 순서는 comp 에 의해 결정됩니다:
[ [ first , last ) 범위에서 bool ( comp ( * iter, value ) ) false 인 첫 번째 반복자 iter 를 반환하며, 해당하는 iter 가 없으면 last 를 반환합니다.
만약 elem 요소들이 [ first , last ) 범위 내에서 표현식 bool ( comp ( elem, value ) ) 에 대해 분할되어 있지 않다면 , 동작은 정의되지 않습니다.

목차

매개변수

first, last - 검사할 요소들의 분할된 범위 를 정의하는 반복자 쌍
value - 요소들과 비교할 값
comp - 첫 번째 인수가 두 번째 인수보다 먼저 정렬된 경우 ​ true 를 반환하는 이항 predicate

predicate 함수의 시그니처는 다음에 해당해야 합니다:

bool pred ( const Type1 & a, const Type2 & b ) ;

시그니처에 const & 가 필요하지는 않지만, 함수는 전달된 객체를 수정해서는 안 되며 값 범주 에 관계없이 (가능한 const) Type1 Type2 타입의 모든 값을 수용할 수 있어야 합니다 (따라서 Type1 & 는 허용되지 않으며 , Type1 Type1 에 대해 이동이 복사와 동등하지 않는 한 허용되지 않습니다 (C++11부터) ).
타입 Type1 ForwardIt 타입의 객체를 역참조한 후 Type1 으로 암시적으로 변환할 수 있어야 합니다. 타입 Type2 T 타입의 객체를 Type2 으로 암시적으로 변환할 수 있어야 합니다. ​

타입 요구사항
-
ForwardIt LegacyForwardIterator 의 요구사항을 충족해야 합니다.
-
Compare BinaryPredicate 의 요구사항을 충족해야 합니다. Compare 를 충족할 필요는 없습니다.

반환값

범위의 첫 번째 요소를 가리키는 반복자 [ first , last ) 에서 value 앞에 정렬되지 않은 첫 번째 요소, 또는 해당 요소가 없으면 last 를 반환합니다.

복잡도

주어진 N std:: distance ( first, last ) 인 경우:

1) 최대 log 2 (N)+O(1) 번의 비교를 value 와 수행하며, 사용하는 비교 연산은 operator < (until C++20) std:: less { } (since C++20) 입니다.
2) 최대 log 2 (N)+O(1) 번의 비교자 comp 적용.

그러나 ForwardIt LegacyRandomAccessIterator 가 아닌 경우, 반복자 증감 횟수는 N 에 선형적으로 비례합니다. 특히, std::map , std::multimap , std::set , 그리고 std::multiset 의 반복자는 임의 접근(random access)이 아니므로, 해당 멤버 함수인 lower_bound 를 사용하는 것이 바람직합니다.

가능한 구현

다음 구현도 참조하십시오: libstdc++ libc++ .

lower_bound (1)
template<class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type>
ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value)
{
    return std::lower_bound(first, last, value, std::less{});
}
lower_bound (2)
template<class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type,
         class Compare>
ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value, Compare comp)
{
    ForwardIt it;
    typename std::iterator_traits<ForwardIt>::difference_type count, step;
    count = std::distance(first, last);
    while (count > 0)
    {
        it = first;
        step = count / 2;
        std::advance(it, step);
        if (comp(*it, value))
        {
            first = ++it;
            count -= step + 1;
        }
        else
            count = step;
    }
    return first;
}

참고 사항

비록 std::lower_bound [ first , last ) 가 분할되기만을 요구하지만, 이 알고리즘은 일반적으로 [ first , last ) 가 정렬된 경우에 사용되므로, 이진 탐색이 어떤 value 에 대해서도 유효합니다.

std::binary_search 와 달리, std::lower_bound operator < 또는 comp 가 비대칭적일 것을 요구하지 않습니다 (즉, a < b b < a 가 항상 다른 결과를 가질 필요가 없습니다). 사실, 이 함수는 value < * iter 또는 comp ( value, * iter ) [ first , last ) 범위 내의 어떤 반복자 iter 에 대해서도 잘 정의될 것을 요구하지 않습니다.

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

예제

#include <algorithm>
#include <cassert>
#include <complex>
#include <iostream>
#include <vector>
struct PriceInfo { double price; };
int main()
{
    const std::vector<int> data{1, 2, 4, 5, 5, 6};
    for (int i = 0; i < 8; ++i)
    {
        // i ≤ x를 만족하는 첫 번째 요소 x를 검색
        auto lower = std::lower_bound(data.begin(), data.end(), i);
        std::cout << i << " ≤ ";
        lower != data.end()
            ? std::cout << *lower << " at index " << std::distance(data.begin(), lower)
            : std::cout << "not found";
        std::cout << '\n';
    }
    std::vector<PriceInfo> prices{{100.0}, {101.5}, {102.5}, {102.5}, {107.3}};
    for (const double to_find : {102.5, 110.2})
    {
        auto prc_info = std::lower_bound(prices.begin(), prices.end(), to_find,
            [](const PriceInfo& info, double value)
            {
                return info.price < value;
            });
        prc_info != prices.end()
            ? std::cout << prc_info->price << " at index " << prc_info - prices.begin()
            : std::cout << to_find << " not found";
        std::cout << '\n';
    }
    using CD = std::complex<double>;
    std::vector<CD> nums{{1, 0}, {2, 2}, {2, 1}, {3, 0}};
    auto cmpz = [](CD x, CD y) { return x.real() < y.real(); };
    #ifdef __cpp_lib_algorithm_default_value_type
        auto it = std::lower_bound(nums.cbegin(), nums.cend(), {2, 0}, cmpz);
    #else
        auto it = std::lower_bound(nums.cbegin(), nums.cend(), CD{2, 0}, cmpz);
    #endif
    assert((*it == CD{2, 2}));
}

출력:

0 ≤ 1 at index 0
1 ≤ 1 at index 0
2 ≤ 2 at index 1
3 ≤ 4 at index 2
4 ≤ 4 at index 2
5 ≤ 5 at index 3
6 ≤ 6 at index 5
7 ≤ not found
102.5 at index 2
110.2 not found

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 270 C++98 Compare Compare 를 만족해야 했고 T
LessThanComparable 이어야 했음 (엄격한 약순서 요구)
분할만 요구됨;
이종 비교 허용
LWG 384 C++98 최대 log(N)+1 비교가 허용됨 log 2 (N)+1 로 수정됨
LWG 2150 C++98 [ first , last ) 범위 내에 bool ( comp ( * iter, value ) ) false
반복자 iter 가 존재할 경우, std::lower_bound
[ iter , last ) 내의 어떤 반복자도 반환할 수 있었음
iter 이후의 반복자는
반환될 수 없음

참고 항목

특정 키와 일치하는 요소들의 범위를 반환합니다
(함수 템플릿)
요소들의 범위를 두 그룹으로 분할합니다
(함수 템플릿)
분할된 범위의 분할 지점을 찾습니다
(함수 템플릿)
특정 값보다 첫 번째 요소에 대한 반복자를 반환합니다
(함수 템플릿)
주어진 키보다 작지 않은 첫 번째 요소에 대한 반복자를 반환합니다
( std::set<Key,Compare,Allocator> 의 public 멤버 함수)
주어진 키보다 작지 않은 첫 번째 요소에 대한 반복자를 반환합니다
( std::multiset<Key,Compare,Allocator> 의 public 멤버 함수)
주어진 값보다 작지 않은 첫 번째 요소에 대한 반복자를 반환합니다
(알고리즘 함수 객체)