libscheaders/functools.hpp

64 lines
1.5 KiB
C++
Raw Permalink Normal View History

2020-03-16 15:11:40 +01:00
#ifndef _functools_H_
#define _functools_H_
#include <vector>
#include <functional>
#include <algorithm>
#include <iterator>
namespace sc {
// std::vector versions
2020-03-16 15:11:40 +01:00
template<class T, class M>
std::vector<M> map(const std::vector<T>& seq, std::function<M(T)> fun) {
std::vector<M> result;
2022-11-01 11:39:09 +01:00
std::transform(seq.begin(), seq.end(), std::back_inserter(result), fun);
2020-03-16 15:11:40 +01:00
return result;
}
template<class T>
std::vector<T> filter(const std::vector<T>& seq, std::function<bool(T)> fun) {
std::vector<T> result;
2022-11-01 11:39:09 +01:00
std::copy_if(seq.begin(), seq.end(), std::back_inserter(result), fun);
2020-03-16 15:11:40 +01:00
return result;
}
template<class T, class R>
R reduce(const std::vector<T>& seq, R seed, std::function<R(T, R)> fun) {
R result {seed};
for (const auto& elem : seq) {
result = fun(elem, result);
}
return result;
}
// iterator versions
template<class T, class M, class FwdIter>
std::vector<M> map(FwdIter begin, FwdIter end, std::function<M(T)> fun) {
std::vector<M> result;
std::transform(begin, end, std::back_inserter(result), fun);
return result;
}
template<class T, class FwdIter>
std::vector<T> filter(FwdIter begin, FwdIter end, std::function<bool(T)> fun) {
std::vector<T> result;
std::copy_if(begin, end, std::back_inserter(result), fun);
return result;
}
template<class T, class R, class FwdIter>
R reduce(FwdIter begin, FwdIter end, R seed, std::function<R(T, R)> fun) {
R result {seed};
for (FwdIter it = begin; it != end; ++it) {
result = fun(*it, result);
}
return result;
}
2020-03-16 15:11:40 +01:00
}
#endif // _functools_H_