![](/img/trans.png)
[英]why it isn't possible to sort a std::map directly using std::sort based upon its value field
[英]Justification/Discussion why std::sort isn't forced to use std::swap
我最近写了代码(相关的SO答案 , 相关代码 ),其交换操作旨在具有与复制构造和复制分配相结合的不同语义。 那就是我认识到std::sort
并不总是使用std::swap
或通过ADL找到的任何swap
函数的地方。
#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;
}
现在,事实在此上多次解决了 std::sort
并不总是使用std::swap
的事实:
我的问题是:在建议或讨论方面,是否考虑过强制std::sort
(和类似的标准库函数)实际使用std::swap
?
在我看来,在指定的条件下……对于我的代码的正确行为,它的交换操作必须具有与复制(移动)构造和复制(移动)分配的组合相同的语义。
我很清楚这样一个事实,即实际的实现(使用副本再进行多次分配)比对任何两个元素进行交换要有效得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.