27Mar/150
c++ for_each on multiple ranges
template<typename InputIter1, typename InputIter2, typename BinaryFunction>
BinaryFunction for_each_on_two_ranges(InputIter1 first1, InputIter1 last1, InputIter2 first2, BinaryFunction f) {
for (; first1 != last1; ++first1, ++first2) {
f(*first1, *first2);
}
return f;
}
or with variadic templates:
void increment_iterator() {}
template<typename Arg1, typename... Args>
void increment_iterator(Arg1& arg1, Args&... args)
{
++arg1;
increment_iterator(args...);
}
template<typename InputIter1, typename Function, typename... InputIters>
Function for_each_N(InputIter1 first1, InputIter1 last1, Function f, InputIters... iters) {
for (; first1 != last1; ++first1) {
f(*first1, *iters...);
increment_iterator(iters...);
}
return f;
}
the following functor can take any parameter:
template<typename T>
struct Add {
Add() : value() {}
void operator()() {}
template<typename U=T, typename... Args>
void operator()(const U& arg1, const Args&... args) {
value+= arg1;
operator()(args...);
}
T value;
};
std::vector<int> a = { 1, 2, 3, 4, 5 };
std::vector<int> b = { 1, 2, 3, 4, 5 };
std::vector<int> c = { 1, 2, 3, 4, 5 };
std::vector<int> d = { 1, 2, 3, 4, 5 };
Add<int> sum2 = for_each_N(a.begin(), a.end(), Add<int>(), b.begin());
Add<int> sum4 = for_each_N(a.begin(), a.end(), Add<int>(), b.begin(), c.begin(), d.begin());
Leave a comment