隣接要素を処理するfor_each

稀によく使うので書いた。const版のみ実装した。

実装:

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 main()
{
    const std::vector<int> v = {1, 2, 3};
 
    adjacent_for_each(v, [](int a, int b) {
        std::cout << a << " : " << b << std::endl;
    });
}

出力:

1 : 2
2 : 3

参照