问题描述
案例1输入
10
1 2 3 1 2 3 1 2 3 1 2 3
案例1输出
a.out: malloc.c:2401: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >
= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' Failed.
Aborted (core dumped)
案例2输入
4
1 2 3 1 2 3 1 2 3 1 2 3
案例2输出
1 1 2 3
我很清楚在两种情况下我都给出了额外的整数作为输入。我的问题是为什么代码在案例1中而不是案例2中给出错误。我正在使用g ++ -pipe -O2 -std = c ++ 11 ./filename.cpp编译我的代码。没有错误或警告。我甚至尝试将vector<int> arr(right)
替换为vector<int> arr(1000000)
,因为情况1仍然是相同的错误。第一行是数组的大小。下一行是数组的元素。用temp[...]
和arr[...]
替换所有temp.at(...)
和arr.at(...)
的情况2下出现错误。
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 6) >= this->size() (which is 6)
Aborted (core dumped)
#include<iostream>
#include<vector>
using namespace std;
void quick_sort_3(vector<int> &arr,int &left,int &right)
{
if(left<right)
{
vector<int> temp(right-left+1);
int pivot=arr[left];
int small=left,large=right;
for(int i=left+1;i<=right;i++)
{
if(arr[i]<pivot)
temp[smalL++]=arr[i];
else if(arr[i]>pivot)
temp[large--]=arr[i];
}
for(int i=left;i<small;i++)
arr[i]=temp[i];
for(int i=small;i<=large;i++)
arr[i]=pivot;
for(int i=large+1;i<=right;i++)
arr[i]=temp[i];
small--;
large++;
quick_sort_3(arr,left,small);
quick_sort_3(arr,large,right);
}
}
int main(void)
{
int left=0,right;
cin>>right;
vector<int> arr(right);
right--;
for(int i=0;i<=right;i++)
cin>>arr[i];
quick_sort_3(arr,right);
for(int i=0;i<=right;i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
解决方法
错误是由于循环temp.at(i)
中的temp[i]
或for(int i=left;i<=right;i++)
引起的。为了解决错误,将使用temp.at(i-left)
或temp[i-left]
。感谢@Kevin的建议以及其他所有人。