libscheaders/functools.hpp
2021-07-26 21:45:13 +02:00

72 lines
1.6 KiB
C++

//
// functools.hpp
// libcommon
//
// Created by Bob Polis at 2019-10-19
// Copyright (c) 2019 SwiftCoder. All rights reserved.
//
#ifndef _functools_H_
#define _functools_H_
#include <vector>
#include <functional>
#include <algorithm>
#include <iterator>
namespace sc {
// std::vector versions
template<class T, class M>
std::vector<M> map(const std::vector<T>& seq, std::function<M(T)> fun) {
std::vector<M> result;
std::transform(seq.begin(), seq.end(), back_inserter(result), fun);
return result;
}
template<class T>
std::vector<T> filter(const std::vector<T>& seq, std::function<bool(T)> fun) {
std::vector<T> result;
std::copy_if(seq.begin(), seq.end(), back_inserter(result), fun);
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;
}
}
#endif // _functools_H_