Funkcja jako argument innej funkcji

0

wiem że w jakimś języku było by tak:

   function reduce(fn, a, init)
    {
        var s = init;
        for (i = 0; i < a.length; i++)
            s = fn( s, a[i] );
        return s;
    }
    
    function sum(a)
    {
        return reduce( function(a, b){ return a + b; }, 
                       a, 0 );
    

Jak przekształcić na c++ (chodzi mi o to żeby była funkcja redukująca inne ( reduce) ?

2

dokładnie to odzwierciedlić można dopiero w nowym standardzie C++11:

#include <functional>
#include <vector>
using namespace std;
 
template <typename T>
T reduce(function<T(T,T)> fn, vector<T> a, T init)
{
   T s = init;
   for (size_t i = 0; i < a.size(); i++)
     s = fn( s, a[i] );
   return s;
}
 
template <typename T>
T sum(vector<T> a)
{
   return reduce( [](T a, T b) -> T { return a + b; }, 
                   a, 0 );
}

(kod nie sprawdzany).

w starym C++ (oraz w C) należałoby użyć wskaźnika na funkcję jako parametr, oraz osobnej funkcji (np. int add(int a, int b) zamiast wyrażenia lambda przy wywołaniu reduce():

#include <vector>
using namespace std;

template <typename T>
T reduce( T (*fn)(T,T), vector<T> a, T init)
{
   T s = init;
   for (size_t i = 0; i < a.size(); i++)
     s = fn( s, a[i] );
   return s;
}

template <typename T>
T add(T a, T b)
{
  return a+b;
}

template <typename T>
T sum(vector<T> a)
{
   return reduce( add, a, 0 );
}

standard C99 pozwana na funkcje lokalne, więc add może być wewnątrz sum. zakładam że operujemy na intach:

int reduce( int (*fn)(int,int), int a[], int len, int init)
{
   int s = init;
   for (int i = 0; i < len; i++)
     s = fn( s, a[i] );
   return s;
}

int sum(int a[], int len)
{
   int add(int a, int b)
   {
     return a+b;
   }
   return reduce( add, a, len, 0 );
}
0

A powiem nawet, że fold jest dostępny w algorithm więc można napisać tak:

std::accumulate(a.begin(), a.end(), 0, [](int a, int b){a + b});

1 użytkowników online, w tym zalogowanych: 0, gości: 1