1

I'm seeking a single meta-function (such as std::less_equal) that can be used or combined in order to express a dominance relationship, defined as follows.

Sequence A dominates another sequence B (both of having equal length) if:

  1. Each element of A is not less than the corresponding element B
  2. At least one element of A is greater than the corresponding element of B

So far the best that I have been able to come up with consists of two separate tests one after the other as 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 it possible do the same using a single metafunction?

3
  • 2
    This isn't a metafunction.
    – T.C.
    Dec 1, 2014 at 22:59
  • I know. std::less_equal is though.
    – Olumide
    Dec 1, 2014 at 23:16
  • So if I understand this correctly, you want a more optimal version of the code you present? Just simply unroll the loop STL would generate for you and merge the two operations.
    – BlamKiwi
    Dec 1, 2014 at 23:53

1 Answer 1

2

The problem with one-pass code is that you have to keep the state - you have to remember whether you encountered the dominating element or not.

Writing a simple for loop would give you an advantage of short-circuiting when you know that the result is false. But if you want a one-liner, here you 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,
        // this accumulates the result
        [](int prevCmp, int curCmp){ return prevCmp > 0 ? prevCmp : (curCmp > 0 ? curCmp : prevCmp + curCmp); },
        // this compares corresponding elements of ranges
        [](const auto& a1, const auto& a2){ return (a1 > a2) - (a2 > a1); }) < 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.