为什么只有当我的容器有超过 32 个元素时 std::sort 才调用交换?

Mae*_*tro 10 c++ swap std

你好,我有一个简单的问题:

class A 
{
public:
    A(int);
    A(const A&);
    A& operator=(const A&);
    ~A();
private:
    int* ptr_;

    friend bool operator<(const A&, const A&);
    friend void swap(A&, A&);
};

A::A(int x) : 
    ptr_(new int(x))
{}

A::A(const A& rhs) :
    ptr_(rhs.ptr_ ? new int(*rhs.ptr_) : nullptr)
{}

A& A::operator = (const A & rhs)
{
    int* tmp = rhs.ptr_ ? new int(*rhs.ptr_) : nullptr;
    delete ptr_;
    ptr_ = tmp;

    return *this;
}

A::~A()
{
    delete ptr_;
}

bool operator<(const A& lhs, const A& rhs)
{
    cout << "operator<(const A&, const A&)" << endl;
    return *lhs.ptr_ < *rhs.ptr_;
}

void swap(A& lhs, A& rhs)
{
    cout << "swap(A&, A&)" << endl;
    using std::swap;
    swap(lhs.ptr_, rhs.ptr_);
}

int main()
{

    std::vector<A> v{ 33,32,31,30,29,28,27,26,25,24,23,22, 21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5, 4,3,2,1 };
    std::sort(v.begin(), v.end());

}
Run Code Online (Sandbox Code Playgroud)

对于超过 32 个元素,排序调用swap. 对于 32 个或更少元素,元素仍会排序但swap不会被调用。

  • 我在 x64 上使用 MSVC++ 2019。
  • 什么时候swap调用,什么时候不调用,为什么?谢谢!
  • 我没有swap在复制赋值中使用,只是为了区分对它的调用和复制赋值运算符的排序。

Evg*_*Evg 15

微软std::sort的实现看起来是这样的:

const int ISORT_MAX = 32;  // maximum size for insertion sort

template<class RanIt, class Diff, class Pr>
void Sort(RanIt First, RanIt Last, Diff Ideal, Pr Pred)
{
    Diff Count;
    for (; ISORT_MAX < (Count = Last - First) && 0 < Ideal; )
    {   // divide and conquer by quicksort
        pair<RanIt, RanIt> Mid = Unguarded_partition(First, Last, Pred);

        // ...
    }

    if (ISORT_MAX < Count)
    {   // heap sort if too many divisions
        Make_heap(First, Last, Pred);
        Sort_heap(First, Last, Pred);
    }
    else if (1 < Count)
        Insertion_sort(First, Last, Pred);  // small
}
Run Code Online (Sandbox Code Playgroud)

当要排序的范围有 32 个或更少元素时,Sort使用插入排序。插入排序swap在其实现中不使用。否则,使用分而治之的快速排序。在实现中,它调用iter_swap(inside Unguarded_partition),后者又调用swap

template<class FwdIt1, class FwdIt2>
void iter_swap(FwdIt1 Left, FwdIt2 Right)
{   // swap *Left and *Right
    swap(*Left, *Right);
}
Run Code Online (Sandbox Code Playgroud)

所有这些都是实现细节。它们因一种标准库实现而异。

  • [libcxx](http://llvm.org/svn/llvm-project/libcxx/trunk/include/algorithm) 根据类型,对长度小于 6 或 30 的序列使用插入排序。[libstd++](https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/include/bits/stl_algo.h) 对 16 个或更少元素的序列执行此操作。[C++11 std::sort 在不同的 STL 实现中使用哪些算法?](/sf/ask/1563746831/) (2认同)