Skip to content

Instantly share code, notes, and snippets.

@NewProggie
Created May 19, 2016 09:13
Show Gist options
  • Save NewProggie/e2a907a8ef16d31e02484cba37a98d9a to your computer and use it in GitHub Desktop.
Save NewProggie/e2a907a8ef16d31e02484cba37a98d9a to your computer and use it in GitHub Desktop.
Process for each adjacent pair in collection
#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