Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

c++ - Is there a standard way to swap arguments for a binary predicate?

I want to find last value in a container that is less-than-or equal using std::lower_bound (that finds greater-than-or-equal), and have a comparison predicate for my type , f.e.

bool valComp(MyType lhs MyType rhs){ return lhs.value_ < rhs.value_; }

Can I somehow concisely call reverse std::lower_bound with reversed arguments to the predicate

std::lower_bound(myVec.rbegin(), myVec.rend(), myVal, std::i_dont_know(valComp));

or am I better off duplicating the predicate / manually swapping them in a lambda / rolling my own template?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A lambda is quite short:

// std::lower_bound(myVec.rbegin(), myVec.rend(), myVal,
    [&valComp](const auto& l, const auto& r) { return valComp(r, l); }
// );

The standard built-in solution would be std::bind

// std::lower_bound(myVec.rbegin(), myVec.rend(), myVal,
    std::bind(valComp, std::placeholders::_2, std::placeholders::_1)
// );

But lambdas are universally more readable. You can make a helper function to make this simpler at the point of use:

template<typename F>
auto swap_two_args(F&& f) {
    return [f=std::forward<F>(f)](auto&& l, auto&& r) {
        return f(std::forward<decltype(r)>(r), std::forward<decltype(l)>(l));
    };
}


// std::lower_bound(myVec.rbegin(), myVec.rend(), myVal,
    swap_two_args(valComp)
// );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...