tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
rotate.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2// SPDX-FileCopyrightText: Copyright (C) 2020 Tobias Hienzsch
3
4#ifndef TETL_ALGORITHM_ROTATE_HPP
5#define TETL_ALGORITHM_ROTATE_HPP
6
7#include <etl/_algorithm/iter_swap.hpp>
8
9namespace etl {
10
11/// \brief Performs a left rotation on a range of elements.
12/// \details Specifically, rotate swaps the elements in the range [first,
13/// last) in such a way that the element n_first becomes the first element of
14/// the new range and n_first - 1 becomes the last element. A precondition of
15/// this function is that [first, n_first) and [n_first, last) are valid ranges.
16/// \ingroup algorithm
17template <typename ForwardIt>
18constexpr auto rotate(ForwardIt first, ForwardIt nFirst, ForwardIt last) -> ForwardIt
19{
20 if (first == nFirst) {
21 return last;
22 }
23 if (nFirst == last) {
24 return first;
25 }
26
27 // Do the first pass (this determines the final return value).
28 auto read = nFirst;
29 auto write = first;
30 auto nextRead = first;
31
32 while (read != last) {
33 if (write == nextRead) {
34 nextRead = read;
35 }
36 etl::iter_swap(write++, read++);
37 }
38
39 auto result = write;
40 first = write;
41 nFirst = nextRead;
42
43 // Finish the remaining work iteratively instead of recursively.
44 while (first != nFirst) {
45 read = nFirst;
46 write = first;
47 nextRead = first;
48
49 while (read != last) {
50 if (write == nextRead) {
51 nextRead = read;
52 }
53 etl::iter_swap(write++, read++);
54 }
55
56 first = write;
57 nFirst = nextRead;
58 }
59
60 return result;
61}
62
63} // namespace etl
64
65#endif // TETL_ALGORITHM_ROTATE_HPP
constexpr auto rotate(ForwardIt first, ForwardIt nFirst, ForwardIt last) -> ForwardIt
Performs a left rotation on a range of elements.
Definition rotate.hpp:18
Definition adjacent_find.hpp:9