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

标签 c++ stl

我为我的类重载了交换函数,如 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/

相关文章:

c++ - 您如何重新分配(也称为集合)unique_ptr 类成员?

C++ 递归指针函数调用

c++ - 带有 odeint 的简单二维系统(使用数组)无法编译

c++ - STL 容器中的自定义析构函数

c++ - 如何将 std::vector<void*> * 作为 std::vector<MyStruct*>* 传递给函数

c++ - 计算一个 boost::range of elements

c++ - 从函数返回迭代器

c++ - std::set::erase(const key_type& key) 如何导致段错误?

c++ - 具有成员 std::map 的结构的赋值

从 Windows 到 Linux 的 C++ 交叉编译器