barretenberg
Loading...
Searching...
No Matches
map.hpp
1#pragma once
2#include <algorithm>
3#include <array>
4#include <type_traits>
5
6/*
7 * Generic map function for mapping a containers element to another type.
8 */
9template <template <typename, typename...> typename Cont,
10 typename InElem,
11 typename... Args,
12 typename F,
13 typename OutElem = typename std::invoke_result<F, InElem const&>::type>
14Cont<OutElem> map(Cont<InElem, Args...> const& in, F&& op)
15{
16 Cont<OutElem> result;
17 std::transform(in.begin(), in.end(), std::back_inserter(result), op);
18 return result;
19}
20
21/*
22 * Generic map function for mapping a std::array's elements to another type.
23 * TODO: this has only been added because I (Mike) couldn't get the above to work
24 * with an array.
25 */
26template <std::size_t SIZE,
27 typename InElem,
28 typename F,
29 typename OutElem = typename std::invoke_result<F, InElem const&>::type>
30std::array<OutElem, SIZE> map(std::array<InElem, SIZE> const& in, F&& op)
31{
32 std::array<OutElem, SIZE> result;
33 std::transform(in.begin(), in.end(), result.begin(), op);
34 return result;
35}
36
37/*
38 * Generic map function for mapping a containers element to another type.
39 * This version passes the element index as a second argument to the operator function.
40 */
41template <template <typename, typename...> typename Cont,
42 typename InElem,
43 typename... Args,
44 typename F,
45 typename OutElem = typename std::invoke_result<F, InElem const&, size_t>::type>
46Cont<OutElem> mapi(Cont<InElem, Args...> const& in, F op)
47{
48 Cont<OutElem> result;
49 for (size_t i = 0; i < in.size(); ++i) {
50 result.push_back(op(in[i], i));
51 }
52 return result;
53}
54
55/*
56 * Generic filter function for containers.
57 */
58template <typename Cont, typename F> Cont filter(Cont const& in, F op)
59{
60 Cont copy(in);
61 std::remove_if(copy.begin(), copy.end(), op);
62 return copy;
63}