gpt4 book ai didi

c++ - 说明/讨论为什么不强制 std::sort 使用 std::swap

转载 作者:行者123 更新时间:2023-11-28 06:07:34 25 4
gpt4 key购买 nike

我最近编写了代码(相关的 SO answerassociated code ),其交换操作旨在具有与复制构造和复制分配的组合不同的语义。这就是我认识到 std::sort 并不总是使用 std::swap 或通过 ADL 找到的任何 swap 函数的地方。

对于那些不熟悉的人,我整理了a small example :

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
namespace thing {
struct thing {
int dummy;
operator int (void) const {
return dummy;
}
thing (int value) : dummy (value) {}
thing (thing const & other) : dummy (other.dummy) {
cout << "copy " << this << " from " << &other << endl;
}
thing & operator=(thing const & other) {
dummy = other.dummy;
cout << "assign " << this << " from " << &other << endl;
}
void swap (thing & other) {
// not called
}
};

void swap (thing & lhs, thing & rhs) {
// not called
}
}

int main() {
vector<thing::thing> data = {1, 21, 42};
cout << "sorting now" << endl;
sort (begin (data), end (data), greater<int>{});
return 0;
}

现在 that std::sort 并不总是使用 std::swap 这一事实已在 SO 上多次解决:

我的问题是:在提案或讨论方面是否有任何考虑强制std::sort(和类似的标准库函数)实际上使用 std::swap?

对我来说,感觉有点……未指定……为了我的代码的正确行为,它的交换操作必须具有与复制(移动)构造和复制(移动)赋值的组合相同的语义。

我很清楚实际的实现(使用一个拷贝后跟多个赋值)比将交换应用于任何两个元素进行排序要有效得多。

最佳答案

当然。参见 issue LWG 226paper N1523

一个主要问题就是调用什么。 ::std::swap 不能重载,不合格的 swap 可能不是正确的函数。事实上,金融行业一直是 C++ 的主要用户,对他们来说 swap 很可能是一个 swap .

关于c++ - 说明/讨论为什么不强制 std::sort 使用 std::swap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com