tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
lower_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_LOWER_BOUND_HPP
5#define TETL_ALGORITHM_LOWER_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/// \brief Returns an iterator pointing to the first element in the range
15/// `[first, last)` that is not less than (i.e. greater or equal to) value, or
16/// last if no such element is found.
17///
18/// https://en.cppreference.com/w/cpp/algorithm/lower_bound
19///
20/// \ingroup algorithm
21template <typename ForwardIt, typename T, typename Compare>
22[[nodiscard]] constexpr auto lower_bound(ForwardIt first, ForwardIt last, T const& value, Compare comp) noexcept
23 -> ForwardIt
24{
25 using diff_t = typename iterator_traits<ForwardIt>::difference_type;
26 ForwardIt it{};
27 diff_t count{};
28 diff_t step{};
29 count = etl::distance(first, last);
30
31 while (count > 0) {
32 it = first;
33 step = count / 2;
34 etl::advance(it, step);
35 if (comp(*it, value)) {
36 first = ++it;
37 count -= step + 1;
38 } else {
39 count = step;
40 }
41 }
42
43 return first;
44}
45
46/// \ingroup algorithm
47template <typename ForwardIt, typename T>
48[[nodiscard]] constexpr auto lower_bound(ForwardIt first, ForwardIt last, T const& value) noexcept -> ForwardIt
49{
50 return etl::lower_bound(first, last, value, less());
51}
52
53} // namespace etl
54
55#endif // TETL_ALGORITHM_LOWER_BOUND_HPP
constexpr auto lower_bound(ForwardIt first, ForwardIt last, T const &value, Compare comp) noexcept -> ForwardIt
Returns an iterator pointing to the first element in the range [first, last) that is not less than (i...
Definition lower_bound.hpp:22
constexpr auto lower_bound(ForwardIt first, ForwardIt last, T const &value) noexcept -> ForwardIt
Definition lower_bound.hpp:48
Definition adjacent_find.hpp:9
iterator_traits is the type trait class that provides uniform interface to the properties of LegacyIt...
Definition iterator_traits.hpp:48
Function object for performing comparisons. Unless specialised, invokes operator< on type T....
Definition less.hpp:15