c++ - Metafunction for expressing "dominance" of one sequence over another -
i'm seeking single meta-function (such std::less_equal
) can used or combined in order express dominance relationship, defined follows.
sequence dominates sequence b (both of having equal length) if:
- each element of not less corresponding element b
- at least 1 element of greater corresponding element of b
so far best have been able come consists of 2 separate tests 1 after other follows.
template<typename t> bool dominates( t& sequence1 , t& sequence2 ) { if( std::equal( sequence1.begin() , sequence1.end() , sequence2.begin() ) ) return false; return std::equal( sequence1.begin() , sequence1.end() , sequence2.begin() , std::less_equal<double>() ); }
is possible same using single metafunction?
the problem one-pass code have keep state - have remember whether encountered dominating element or not.
writing simple for
loop give advantage of short-circuiting when know result false
. if want one-liner, here go:
template<typename t> bool dominates2(const t& sequence1, const t& sequence2) { return std::inner_product(std::begin(sequence1), std::end(sequence1), std::begin(sequence2), 0, // accumulates result [](int prevcmp, int curcmp){ return prevcmp > 0 ? prevcmp : (curcmp > 0 ? curcmp : prevcmp + curcmp); }, // compares corresponding elements of ranges [](const auto& a1, const auto& a2){ return (a1 > a2) - (a2 > a1); }) < 0; }
Comments
Post a Comment