Last active
June 21, 2017 09:36
-
-
Save faithandbrave/370155a2078b158853b3 to your computer and use it in GitHub Desktop.
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
// 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. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Known issues:
first
iterator advance twice (++first
andstd::next(first)
).