tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
shift_left.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_SHIFT_LEFT_HPP
5#define TETL_ALGORITHM_SHIFT_LEFT_HPP
6
7#include <etl/_algorithm/move.hpp>
8#include <etl/_concepts/emulation.hpp>
9#include <etl/_iterator/iterator_traits.hpp>
10
11namespace etl {
12
13/// \brief Shifts the elements in the range [first, last) by n positions.
14///
15/// \details Shifts the elements towards the beginning of the range. If n == 0
16/// or n >= last - first, there are no effects. If n < 0, the behavior is
17/// undefined. Otherwise, for every integer i in [0, last - first - n), moves
18/// the element originally at position first + n + i to position first + i. The
19/// moves are performed in increasing order of i starting from ​0​.
20///
21/// \ingroup algorithm
22template <typename ForwardIt>
23constexpr auto shift_left(ForwardIt first, ForwardIt const last, typename iterator_traits<ForwardIt>::difference_type n)
24 -> ForwardIt
25{
26 // The standard only checks for n == 0. n < 0 would be undefined behavior.
27 // This implementation does nothing if n < 0.
28 if (n <= 0) {
29 return last;
30 }
31
32 auto start = first;
33 if constexpr (etl::detail::RandomAccessIterator<ForwardIt>) {
34 if (n >= last - first) {
35 return first;
36 }
37 start += n;
38 } else {
39 for (; 0 < n; --n) {
40 if (start == last) {
41 return first;
42 }
43 ++start;
44 }
45 }
46
47 first = etl::move(start, last, first);
48 return first;
49}
50
51} // namespace etl
52
53#endif // TETL_ALGORITHM_SHIFT_LEFT_HPP
constexpr auto shift_left(ForwardIt first, ForwardIt const last, typename iterator_traits< ForwardIt >::difference_type n) -> ForwardIt
Shifts the elements in the range [first, last) by n positions.
Definition shift_left.hpp:23
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