Sorting Std排序使Std::vector无效
我在std::sort中发现了一个bug,特别是在一些QuickSort的实现中,我不知道问题是否出在一般的算法中 精髓: 当元素小于16时,所有的规范都被替换,因为std::sort使用插入排序 当有17个或更多的元素时,使用快速排序,并限制元素数对数的递归深度,但向量在第一次_introsort_循环迭代时有时间恶化 当有许多相同的元素时,就会出现向量损坏。用无效迭代器替换有效迭代器时发生损坏 其他容器也可能破裂,我没有检查 对于更复杂的对象,使用类型为“int”的向量简化示例-排序时崩溃,因为无效对象被传递给比较函数:Sorting Std排序使Std::vector无效,sorting,std,quicksort,Sorting,Std,Quicksort,我在std::sort中发现了一个bug,特别是在一些QuickSort的实现中,我不知道问题是否出在一般的算法中 精髓: 当元素小于16时,所有的规范都被替换,因为std::sort使用插入排序 当有17个或更多的元素时,使用快速排序,并限制元素数对数的递归深度,但向量在第一次_introsort_循环迭代时有时间恶化 当有许多相同的元素时,就会出现向量损坏。用无效迭代器替换有效迭代器时发生损坏 其他容器也可能破裂,我没有检查 对于更复杂的对象,使用类型为“int”的向量简化示例-排序时崩溃,
#include <iostream>
#include <vector>
#include <algorithm>
void quickSort(int arr[], int left, int right) {
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
/* partition */
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
/* recursion */
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
int main()
{
for( int i = 0 ; i < 1 ; i++ )
{
//std::vector<int> v({5, 6, 1, 6, 2, 6, 3, 6, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6});//reproducible with this
std::vector<int> v(19, 6);//reproducible with this also
std::sort(std::begin(v), std::end(v), [&v]( const int & left, const int & right )
{
// std::cout << " left=" << left << ", right=" << right << std::endl;
bool b = left <= right;
return b;
}
);
// quickSort(v.data(), 0, v.size());
for( const auto & result : v )
{
std::cout << "results: " << result << std::endl;
}
}
std::cout << "Hello World!\n";
}
#包括
#包括
#包括
无效快速排序(int-arr[],int-left,int-right){
int i=左,j=右;
int tmp;
int pivot=arr[(左+右)/2];
/*分割*/
而(我)
j--;
如果(i我试过你的代码,但问题似乎出在使用构造函数向量(n,val)(填充构造函数)创建的向量上。手动插入16、17、18和19个随机元素时,向量不会出现问题。你必须在类的开头保存枢轴,如
无效快速排序(int-arr[],int-left,int-right){
int i=左,j=右;int pivot=x[左];
在那之后,将工作用相同的值手动重新创建向量似乎也没有问题。填充构造函数肯定有问题。我对手动填充向量有问题。我在排序“结果:0,0,0,1,2,3,4,4,4,4,4,6,6,6,6,6,6”后得到了结果。我有gcc版本“gcc版本6.4.0 20180424”(Ubuntu 6.4.0-17ubuntu1~16.04)”。你的是什么?我再次运行了代码,结果表明,如果lambda表达式被替换为“left