本质上,我在一些情况下使用 boost::filter_iterator
为某些条件过滤迭代器。有一种情况,我想同时过滤 2 个条件,我们已经有一些预先存在的代码,但我想知道是否有一种惯用的方法可以使用 boost 或标准库来做到这一点:
/*! TODO: Surely there should be something in std/boost to achieve this??? */
/*! Filter for things that satisfy F1 and F2 */
template <
typename F1,
typename F2,
typename ArgT
>
struct filter_and
{
F1 f1;
F2 f2;
filter_and(F1 _f1, F2 _f2): f1(_f1), f2(_f2)
{}
inline bool operator() (ArgT const& arg) const
{
return f1(arg) && f2(arg);
}
};
如果一个解决方案需要 c++11,只要最新的 MSVC 可以处理它应该没问题。
最佳答案
试试这个:make_filter_iterator( it, [=](value_type const& v) { return f1(v) && f2(v); } );
对于更高级的...
bool and_in_order() { return true; }
template<typename F0, typename Funcs...>
bool and_in_order( F0&& f0, Funcs&&... funcs ) {
return f0() && and_in_order(funcs...);
}
template<typename... Funcs>
struct and_unary_functors {
std::tuple<Funcs...> funcs;
template<typename Arg, typename seq=typename make_seq<sizeof...(Funcs)>::type>
bool operator()(Arg&& arg) const;
template<typename Arg, int...s>
bool operator()<Arg, seq<s...>>(Arg&& arg) const {
return and_in_order( [&](){ return get<s>(funcs)(arg); }... );
}
};
template<typename... Funcs>
and_unary_functors<Funcs> make_and_unary( Funcs const&... funcs ) {
return {std::make_tuple(funcs...)};
};
auto filter_it = make_filter_iterator( base_iterator, make_and_unary( f1, f2, f3, f4 ) );
或者类似的傻事。
关于c++ - 使用 boost MPL 或类似工具执行此迭代器过滤器的任何方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15098390/