Is there a nice way to assign std::minmax(a, b) to std::tie(a, b)?

后端 未结 3 711
暗喜
暗喜 2021-02-04 23:33
std::tie(a, b) = std::minmax(a, b);

I think this is intuitive code. Clean and understandable. Too bad it doesn\'t work as intended, as std::minmax temp

3条回答
  •  无人共我
    2021-02-04 23:53

    Sometimes, taking a step back and finding a different way pays off:

    if (b < a)
        std::iter_swap(&a, &b);
    

    That's concise and generally more efficient, certainly at least on par. Maybe pack it into its own function:

    template 
    void reorder(T& a, T& b)
    noexcept(noexcept(b < a, void(), std::iter_swap(&a, &b))) {
        if (b < a)
            std::iter_swap(&a, &b);
    }
    

    I'm using std::iter_swap() so I don't have to use the using std::swap; swap(a, b) two-step for generality in pre-C++2a, which introduces customization point objects making that obsolete.

提交回复
热议问题