C++ 为什么只有当我的容器包含超过32个元素时,std::sort才会调用swap?
你好,我有一个简单的问题:C++ 为什么只有当我的容器包含超过32个元素时,std::sort才会调用swap?,c++,std,swap,C++,Std,Swap,你好,我有一个简单的问题: 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) :
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());
}
A类
{
公众:
A(int);
A(常数A&);
A&运算符=(常数A&);
~A();
私人:
int*ptr_2;;
friend bool operatorMicrosoftstd::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
}
所有这些都是实现细节。它们因标准库实现而异。std::sort
如果元素数为32或更少,则使用插入排序,否则使用快速排序。@Evg这是一个要求还是对这个特定上下文的解释?@FrançoisAndrieux,这是一个实现Microsoft标准库的详细信息。我猜这就是OP观察到的行为的原因。我目前正在查看源代码以获得更多详细信息。源代码的相关部分是:while(
其中\u ISORT\u MAX
的值为32。使用VS 16.5.0的
的第3447行没有在任何语言的现代标准库中使用真正的快速排序。所有这些库都使用修改过的混合版本,只有在元素数量足够大时才是快速排序。例如,Java和Python使用while.NET framework和GCC使用LBSTDC++和LBC++也可以使用短序列的插入排序。请参见根据类型的插入排序小于6或30的序列。对于16个元素或更少的序列,是否使用插入排序。
template<class FwdIt1, class FwdIt2>
void iter_swap(FwdIt1 Left, FwdIt2 Right)
{ // swap *Left and *Right
swap(*Left, *Right);
}