Files
spark/src/lib/utils/sane_algorithm.h
T

60 lines
1.5 KiB
C++

#pragma once
#include <algorithm>
namespace bts {
namespace sane {
template <class T, class TCollection, class TGet>
T max(const TCollection &collection, TGet get) {
auto max = std::numeric_limits<T>::min();
for (const auto &item : collection) {
if (max < get(item)) {
max = get(item);
}
}
return max;
}
template <class T, class TCollection, class TGet>
T min(const TCollection &collection, TGet get) {
auto min = std::numeric_limits<T>::max();
for (const auto &item : collection) {
if (min > get(item)) {
min = get(item);
}
}
return min;
}
// Calculate min using transform on T (i.e. a member accessor)
template <class T, class TProperty, class TCollection, class TGet>
const T *min_by(const TCollection &collection, TGet get) {
auto min = std::numeric_limits<TProperty>::max();
const T *pitem = nullptr;
for (const auto &item : collection) {
if (min > get(item)) {
min = get(item);
pitem = &item;
}
}
return pitem;
}
template <class TCollection, class TWhat>
bool true_for_all(const TCollection &collection, TWhat what) {
for (const auto &item : collection) {
if (!what(item))
return false;
}
return true;
}
template <class TSrc, class TDest, class TFn>
void map(const TSrc &source, TDest &dest, const TFn &fn) {
std::transform(
std::begin(source), std::end(source), std::inserter(dest, dest.end()),
fn);
}
} // namespace sane
} // namespace bts