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

后端 未结 3 708
暗喜
暗喜 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-05 00:01

    You can enforce this with a certain level of brevity as follows.

    std::tie(a, b) = std::minmax(+a, +b);
    
    std::cout << "a: " << a << ", b: " << b << '\n';
    

    Explanation: the builtin unary plus operator, for the sake of symmetry with its unary minus sibling, returns its operand by value (it also performs the usual arithmetic conversions, but that doesn't apply to ints). This means it has to create a temporary, even though this temporary is nothing but a copy of the operand. But for the usage of minmax in this example, it's sufficient: swapping references here doesn't assign through anymore, because the references on the right hand side (the const int& arguments passed to minmax) don't refer to the same objects as those on the left hand side (inside the tuple of references created by std::tie).

    The output is as desired:

    a: 5, b: 7

提交回复
热议问题