std::lower_bound
cppreference.com
<algorithm> 에 정의되어 있음.
|
||
template< class ForwardIt, class T > ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value ); |
(1) | |
template< class ForwardIt, class T, class Compare > ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp ); |
(2) | |
범위 [first, last)
에서 value보다 작지 않은(즉, 크거나 같은) 첫번째 요소를 가리키는 iterator를 반환합니다.
범위 [first, last)
는 반드시 정렬되어 있어야 합니다. element < value나 comp(element, value) 같은 식으로 분할가능해야 합니다. std::partition가 반환한 영역처럼 완전히 정렬된 범위를 사용해야 합니다.
첫번째 버전은 요소를 비교하기 위해 operator<를 사용합니다. 두번째 버전은 주어진 comp
함수를 사용합니다.
목차 |
[편집] Parameters
first, last | - | 검사를 위해 부분적으로 정렬된 범위를 정의하는 iterator |
value | - | 요소와 비교할 값 |
comp | - | comparison function which returns true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b); The signature does not need to have const &, but the function must not modify the objects passed to it. |
형식의 필요조건 | ||
-ForwardIt 는 다음 조건을 만족해야 한다 : ForwardIterator .
|
[편집] Return value
value
보다 작지 않은 첫번째 요소를 가리키는 iterator를 반환합니다. 조건을 만족하는 요소가 없으면 last
를 반환합니다.
[편집] Complexity
first
와 last
사이의 거리에서 로그 횟수의 비교를 수행합니다.
[편집] Possible implementation
First version |
---|
template<class ForwardIt, class T> ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value) { 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 (*it < value) { first = ++it; count -= step + 1; } else count = step; } return first; } |
Second version |
template<class ForwardIt, class T, 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; } |
[편집] Example
코드 실행
#include <algorithm> #include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> data = { 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6 }; auto lower = std::lower_bound(data.begin(), data.end(), 4); auto upper = std::upper_bound(data.begin(), data.end(), 4); std::copy(lower, upper, std::ostream_iterator<int>(std::cout, " ")); }
Output:
4 4 4
[편집] See also
returns range of elements matching a specific key (function template) | |
divides a range of elements into two groups (function template) | |
returns an iterator to the first element greater than a certain value (function template) |