boost::adaptors::adjacent_filter

References

Headers

boost::adaptors::adjacent_filter is available by including any of the following headers:

  • boost/range/adaptor/adjacent_filtered.hpp or
  • boost/range/adaptors.hpp or
  • boost/range/adaptor/uniqued.hpp

Examples

adjacent_filter-function.cpp

#include <iostream>
#include <set>
#include <vector>

#include <boost/range/adaptors.hpp>

const std::vector<int> vec = { 0, 1, 2, 3, 4 };


/** Binary predicate that returns true as long as lhs != constructor_arg */
class lhs_neq {
public:
    explicit lhs_neq(int n) : _n(n) {}

    bool operator()(int lhs, int rhs) {
        bool result = (lhs != _n);
        std::cout << "  called lhs_neq(" << lhs << ", " << rhs << ") -> "
                  << (result ? "true" : "false") << std::endl;
        return result;
    }

private:
    int _n;
};


/** Print the results of the adjacent_filter calls in a readable way */
void print_result(int n, const std::set<int> &seen_values) {
    std::cout << "Pair where lhs = " << n << " removed. Result = {";
    for (int i : vec) {
        if (seen_values.count(i)) {
            std::cout << i << ", ";
        } else {
            std::cout << "   ";
        }
    }
    std::cout << "}" << std::endl;
}


int main() {
    for (int n : {0, 1, 2, 3, 4}) {
        std::set<int> seen_values;

        // adjacent_filter() calls the binary predicate for every consecutive
        // pair of values in the input range. If the predicate returns false,
        // the first value of the pair is removed from the result range.
        //
        // The last value in the input range is always included (there is no
        // pair where it's the first of the two values).
        for (int i : boost::adaptors::adjacent_filter(vec, lhs_neq(n))) {
            seen_values.insert(i);
        }
        print_result(n, seen_values);
    }

    return 0;
}

Output:

  called lhs_neq(0, 1) -> false
  called lhs_neq(1, 2) -> true
  called lhs_neq(2, 3) -> true
  called lhs_neq(3, 4) -> true
Pair where lhs = 0 removed. Result = {   1, 2, 3, 4, }
  called lhs_neq(0, 1) -> true
  called lhs_neq(1, 2) -> false
  called lhs_neq(2, 3) -> true
  called lhs_neq(3, 4) -> true
Pair where lhs = 1 removed. Result = {0,    2, 3, 4, }
  called lhs_neq(0, 1) -> true
  called lhs_neq(1, 2) -> true
  called lhs_neq(2, 3) -> false
  called lhs_neq(3, 4) -> true
Pair where lhs = 2 removed. Result = {0, 1,    3, 4, }
  called lhs_neq(0, 1) -> true
  called lhs_neq(1, 2) -> true
  called lhs_neq(2, 3) -> true
  called lhs_neq(3, 4) -> false
Pair where lhs = 3 removed. Result = {0, 1, 2,    4, }
  called lhs_neq(0, 1) -> true
  called lhs_neq(1, 2) -> true
  called lhs_neq(2, 3) -> true
  called lhs_neq(3, 4) -> true
Pair where lhs = 4 removed. Result = {0, 1, 2, 3, 4, }

 

Boost Range for Humans

This reference is part of Boost Range for Humans. Click the link to the overview.