gpt4 book ai didi

c++ - 忽略交换函数的重载

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:07:18 26 4
gpt4 key购买 nike

我为我的类重载了交换函数,如 this answer ,但在排序时 (std::sort) 编译器仍在使用 std::swap。我看不出我的方法与链接答案中所述的方法有任何区别。这是我的代码的复制:

#include <vector>
#include <iterator>
#include <algorithm>
#include <iostream>

struct B
{
struct A
{
friend void swap(A & a, A & b)
{
std::swap(a.a, b.a);
std::cout << "my swap\n";
}

A(int _a) : a(_a) {}
bool operator<(const A & other) { return a < other.a; }
int a;
};
};

int main()
{
std::vector<B::A> v{1, 2, 3, 5, 4};
std::sort(std::begin(v), std::end(v));
}

还提供了可执行示例 here .

最佳答案

该标准在其规范(§25.4.1.1 [alg.sort])中并未说明 std::sort 实际上保证调用 swap,它只提到类型必须满足某些我不会解释为保证的概念:

Requires: RandomAccessIterator shall satisfy the requirements of ValueSwappable (17.6.3.2). The type of *first shall satisfy the requirements of MoveConstructible (Table 20) and of MoveAssignable (Table 22).

因此它只是可以调用它,这取决于实现。 This answer也可能会提供一些相关信息。

关于c++ - 忽略交换函数的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47113457/

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