std::tie(a, b) = std::minmax(a, b);
我认为这是直观的代码。干净且易于理解。太糟糕了,它没有按预期工作,因为std::minmax https://en.cppreference.com/w/cpp/algorithm/minmax模板用于const&
。因此,如果这些值在内部交换std::pair<const&, const&>
一个赋值将覆盖另一个值:
auto[a, b] = std::make_pair(7, 5);
std::tie(a, b) = std::minmax(a, b);
std::cout << "a: " << a << ", b: " << b << '\n';
甲:5,乙:5
这里的预期输出是a: 5, b: 7
.
我认为这很重要,因为实现转换函数以将函数应用到某些范围需要这样的直观 lambda 语句。例如:
std::vector<int> v{ 0, 1, 0, 2, 0 };
std::vector<int> u{ 1, 0, 1, 0, 1 };
perform(v.begin(), v.end(), u.begin(), [](auto& a, auto& b){
std::tie(a, b) = std::minmax(a, b);
});
//v would be == {0, 0, 0, 0, 0}
//u would be == {1, 1, 1, 2, 1}
我发现的一个解决方案是构建一个std::tuple https://en.cppreference.com/w/cpp/utility/tuple明确地没有任何引用限定符std::pair<const&, const&>
强制执行副本:
std::tie(a, b) = std::tuple<int, int>(std::minmax(a, b));
但是这个<int, int>
冗余似乎相当糟糕,尤其是当我说auto& a, auto& b
前。
有没有一种好的、简短的方法来执行这项任务?难道这是方向错误,只是说if (a >= b) { std::swap(a, b); }
这是最好的方法吗?