Created
May 19, 2016 09:13
-
-
Save NewProggie/e2a907a8ef16d31e02484cba37a98d9a to your computer and use it in GitHub Desktop.
Process for each adjacent pair in collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
// process for each adjacent pair in collection: | |
// [2, 3, 5, 7, 9] ==> f(2, 3), f(3, 5), f(5, 7), f(7, 9) | |
template <typename Iter, typename Func> | |
void adjacent_pair(Iter first, Iter last, Func f) { | |
auto trailer = first; | |
first++; | |
while (first != last) { | |
f(*trailer, *first); | |
first++; | |
trailer++; | |
} | |
} | |
struct PairPrinter { | |
void operator()(int a, int b) { | |
std::cout << "(" << a << "," << b << "), "; | |
} | |
}; | |
void PairPrinterF(int a, int b) { std::cout << "f(" << a << "," << b << "), "; } | |
int main(int argc, char *argv[]) { | |
std::vector<int> foo = {2, 3, 5, 7, 9}; | |
for (auto i : foo) std::cout << i << " "; | |
std::cout << std::endl; | |
adjacent_pair(foo.begin(), foo.end(), PairPrinterF); | |
std::cout << std::endl; | |
adjacent_pair(foo.begin(), foo.end(), [](int a, int b) { | |
std::cout << "l(" << a << "," << b << "), "; | |
}); | |
std::cout << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment