docp
docp

Reputation: 327

Do every operation twice

I would like to every function to be done twice. Arguments are in array, so it is something like this:

fun1(A[0]);
fun1(A[1]);

fun2(A[0]);
fun2(A[1]);

fun3(A[0]);
fun3(A[1]);

Is there a way to do it automatically? I cannot use

for(int i=0; i<2; i++)

cause it will be:

fun1(A[0]);
fun2(A[0]);
fun3(A[0]);

fun1(A[1]);
fun2(A[1]);
fun3(A[1]);

And order in that case matters.

Upvotes: 0

Views: 113

Answers (3)

sv90
sv90

Reputation: 527

You can wrap that behaviour in a higher order function that applies a function twice and apply that function on you functions.

Using C++17 fold expressions that function could look as easy as

template <typename Func, typename Arr, typename... Indices>
void map_indices(Func&& f, Arr&& arr, Indices&&... is) {
  (f(arr[is]), ...);
}

Using C++11 or C++14 this can be implemented using recursion.

Your example would then look like

#include <array>
#include <iostream>

template <typename Func, typename Arr, typename... Indices>
void map_indices(Func&& f, Arr&& arr, Indices&&... is) {
  (f(arr[is]), ...);
}

void f1(int x) {
  std::cout << "f1 " << x << '\n';
}

void f2(int x) {
  std::cout << "f2 " << x << '\n';
}

void f3(int x) {
  std::cout << "f3 " << x << '\n';
}

int main() {
  std::array arr{1, 2, 3};
  map_indices(f1, arr, 0, 1);
  map_indices(f2, arr, 0, 1);
  map_indices(f3, arr, 0, 1);
}

If you know that you will only need the indices 0 and 1 map_indices can be simplified to

template <typename Func, typename Arr>
void map_indices(Func&& f, Arr&& arr) {
  f(arr[0]);
  f(arr[1]);
}

Upvotes: 0

Neo
Neo

Reputation: 46

Here is a C version (ignoring std namespace) for storing an array of functions, just in case you cannot use the solution provided by @CoryKramer.

typedef void (*PointerFunction)(int x);

void functA(int a) {
    std::cout << "functA: " << a << std::endl;
}
void functB(int b) {
    std::cout << "functB: " << b << std::endl;
}

PointerFunction functions[] = { functA, functB };

for (int func = 0; func < 2; func++) {
    for (int i = 0; i < 2; i++) {
        functions[func](i);
    }
}

Upvotes: 3

Cory Kramer
Cory Kramer

Reputation: 117876

You can use function pointers to loop through all the functions you want to call on each of the elements in your container. For example

#include <iostream>
#include <vector>

void fun1(int i)
{
    std::cout << "fun1: " << i << "\n";
}

void fun2(int i)
{
    std::cout << "fun2: " << i << "\n";
}

int main()
{
    using fn_t = void(*)(int);
    std::vector<fn_t> funs{&fun1, &fun2};
    std::vector<int> A = {2, 5};

    for (auto& f : funs)
    {
        for (int i : A)
        {
            f(i);
        }
    }
}

Output

fun1: 2
fun1: 5
fun2: 2
fun2: 5

Upvotes: 5

Related Questions