I know the challenge is officially over, but i saw noone gave a C++ solution, so i thought i should give it a try (and refresh my template skills which i haven't used for a long time).
Code:
#include <iostream>
#include <vector>
template <typename Function, typename T>
std::vector<T> map(Function f, std::vector<T> const &data)
{
std::vector<T> result;
for (typename std::vector<T>::const_iterator it = data.begin();
it != data.end();
++it)
result.push_back(f(*it));
return result;
}
template <typename T>
class Square
{
public:
T operator()(T const &x)
{
return x * x;
}
};
template <typename Function, typename T>
std::vector<T> filter(Function f, std::vector<T> const &data)
{
std::vector<T> result;
for (typename std::vector<T>::const_iterator it = data.begin();
it != data.end();
++it)
if (f(*it))
result.push_back(*it);
return result;
}
class isOdd
{
public:
int operator()(int x)
{
return x & 1;
}
};
template <typename Function, typename T>
T reduce(Function f, std::vector<T> const & data, T const &i)
{
T value = i;
for (typename std::vector<T>::const_iterator it = data.begin();
it != data.end();
++it)
value = f(value, *it);
return value;
}
template <typename T>
class add
{
public:
T operator()(T const &v1, T const &v2)
{
return v1 + v2;
}
};
template <typename T>
void print(std::vector<T> const &data)
{
for (typename std::vector<T>::const_iterator it = data.begin();
it != data.end();
++it)
std::cout << *it << ' ';
std::cout << '\n';
}
int main()
{
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::vector<int> vec(array, array + 10);
std::vector<int> squares = map(Square<int>(), vec);
print(squares);
std::vector<int> odds = filter(isOdd(), vec);
print(odds);
std::vector<int> vec2(array, array + 5);
int sum = reduce(add<int>(), vec2, 0);
std::cout << sum << std::endl;
return 0;
}
Bookmarks