tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
upper_bound.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2// SPDX-FileCopyrightText: Copyright (C) 2019 Tobias Hienzsch
3
4#ifndef TETL_ALGORITHM_UPPER_BOUND_HPP
5#define TETL_ALGORITHM_UPPER_BOUND_HPP
6
7#include <etl/_functional/less.hpp>
8#include <etl/_iterator/advance.hpp>
9#include <etl/_iterator/distance.hpp>
10#include <etl/_iterator/iterator_traits.hpp>
11
12namespace etl {
13
14/// \ingroup algorithm
15/// @{
16
17/// Returns an iterator pointing to the first element in the range `[first, last)`
18/// that is greater than `value`, or last if no such element is found.
19///
20/// The range `[first, last)` must be partitioned with respect to the
21/// expression `not (value < element)` or `not comp(value, element)`, i.e., all
22/// elements for which the expression is true must precede all elements for
23/// which the expression is false. A fully-sorted range meets this criterion.
24template <typename ForwardIt, typename T, typename Compare>
25[[nodiscard]] constexpr auto upper_bound(ForwardIt first, ForwardIt last, T const& value, Compare comp) -> ForwardIt
26{
27 auto count = etl::distance(first, last);
28 while (count > 0) {
29 auto it = first;
30 auto step = count / 2;
31 etl::advance(it, step);
32 if (not comp(value, *it)) {
33 first = ++it;
34 count -= step + 1;
35 } else {
36 count = step;
37 }
38 }
39
40 return first;
41}
42
43template <typename ForwardIt, typename T>
44[[nodiscard]] constexpr auto upper_bound(ForwardIt first, ForwardIt last, T const& value) -> ForwardIt
45{
46 return etl::upper_bound(first, last, value, etl::less());
47}
48
49/// @}
50
51} // namespace etl
52
53#endif // TETL_ALGORITHM_UPPER_BOUND_HPP
constexpr auto upper_bound(ForwardIt first, ForwardIt last, T const &value) -> ForwardIt
Definition upper_bound.hpp:44
constexpr auto upper_bound(ForwardIt first, ForwardIt last, T const &value, Compare comp) -> ForwardIt
Definition upper_bound.hpp:25
Definition adjacent_find.hpp:9
Function object for performing comparisons. Unless specialised, invokes operator< on type T....
Definition less.hpp:15