Skip to content

Instantly share code, notes, and snippets.

@faithandbrave
Last active June 21, 2017 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faithandbrave/370155a2078b158853b3 to your computer and use it in GitHub Desktop.
Save faithandbrave/370155a2078b158853b3 to your computer and use it in GitHub Desktop.
// Copyright Akira Takahashi 2015
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <iterator>
template <class InputRange, class BinaryFunction>
void adjacent_for_each(const InputRange& range, BinaryFunction f)
{
// for ADL
using std::begin;
using std::end;
auto first = begin(range);
auto last = end(range);
if (first == last)
return;
while (std::next(first) != last) {
const auto& a = *first;
++first;
const auto& b = *first;
f(a, b);
}
}
#include <iostream>
#include <vector>
int test();
int main()
{
const std::vector<int> v = {1, 2, 3};
adjacent_for_each(v, [](int a, int b) {
std::cout << a << " : " << b << std::endl;
});
return test();
}
#include <utility>
#include <boost/detail/lightweight_test.hpp>
int test()
{
{
const std::vector<int> input = {1, 2, 3};
const std::vector<std::pair<int, int>> expected = {
{1, 2},
{2, 3}
};
std::vector<std::pair<int, int>> result;
adjacent_for_each(input, [&result](int a, int b) {
result.push_back(std::make_pair(a, b));
});
BOOST_TEST(result == expected);
}
{
const std::vector<int> input = {1};
adjacent_for_each(input, [](int, int) {
BOOST_TEST(false);
});
}
{
const std::vector<int> input = {};
adjacent_for_each(input, [](int, int) {
BOOST_TEST(false);
});
}
return boost::report_errors();
}
/*
output:
1 : 2
2 : 3
No errors detected.
*/
@faithandbrave
Copy link
Author

Known issues:

  • Input Iterator requires single-traversal. Now, first iterator advance twice (++first and std::next(first)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment