为什么只有我的容器中有32个以上的元素时,std :: sort才会调用swap?

问题描述 投票:11回答:1

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

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());

}

具有32个以上的元素,排序调用swap。对于32个或更少的元素,这些元素仍会排序,但不会调用swap

  • 我在x64上使用MSVC ++ 2019。
  • 何时调用swap,何时不调用,为什么?谢谢!
  • 我没有在复制分配中使用swap只是为了区分来自复制分配运算符的对该调用的排序方式。
c++ std swap
1个回答
13
投票

像这样的Microsoft std::sort实现looks

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
}

当要排序的范围不超过32个元素时,Sort使用插入排序。插入排序在其swap中不使用implementation。否则,将使用分治法快速排序。在implementation中,它调用iter_swap(在Unguarded_partition内部),which依次调用swap

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

所有这些都是实现细节。从一个标准库实现到另一个标准库实现,它们有所不同。

© www.soinside.com 2019 - 2024. All rights reserved.