Algorithm.hpp 2.11 KB
Newer Older
1
2
3
#pragma once

#include <algorithm>
4
5
#include <functional>
#include <utility>
6
7
8

namespace AMDiS
{
9
10
11
12
  /// \brief Split a sequence `[first,last)` by the separators `sep` and pass the tokens as
  /// begin-end iterator pair to the provided functor `f = void(InputIterator, InputIterator)`
  template <class InputIter, class Tp, class BinaryFunc>
  void split(InputIter first, InputIter last, Tp sep, BinaryFunc f)
13
  {
14
    if (first == last)
15
16
17
      return;

    while (true) {
18
      InputIter found = std::find(first, last, sep);
19
      f(first, found);
20
      if (found == last)
21
22
23
24
25
        break;
      first = ++found;
    }
  }

26
27
28
29
  /// \brief Split a sequence `[first,last)` by any of the separators `[s_first, s_last)` and pass the tokens as
  /// begin-end iterator pair to the provided functor `f = void(InputIterator, InputIterator)`
  template <class InputIter, class SeparaterIter, class BinaryFunc>
  void split(InputIter first, InputIter last, SeparaterIter s_first, SeparaterIter s_last, BinaryFunc f)
30
  {
31
    if (first == last)
32
33
34
      return;

    while (true) {
35
      InputIter found = std::find_first_of(first, last, s_first, s_last);
36
      f(first, found);
37
      if (found == last)
38
39
40
41
        break;
      first = ++found;
    }
  }
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

  /// \brief Output the cumulative sum of one range to a second range
  // NOTE: backport of std::exclusive_scan from c++17
  template <class InputIter, class OutputIter, class Tp, class BinaryOperation>
  OutputIter exclusive_scan(InputIter first, InputIter last,
                            OutputIter result, Tp init, BinaryOperation binary_op)
  {
    while (first != last) {
      auto v = init;
      init = binary_op(init, *first);
      ++first;
      *result++ = std::move(v);
    }
    return result;
  }

  /// \brief Output the cumulative sum of one range to a second range
  // NOTE: backport of std::exclusive_scan from c++17
  template <class InputIter, class OutputIter, class Tp>
  inline OutputIter exclusive_scan(InputIter first, InputIter last,
                                   OutputIter result, Tp init)
  {
    return AMDiS::exclusive_scan(first, last, result, std::move(init), std::plus<>());
  }

67
}