我正在尝试制作一个简单的快速排序算法,每当我运行它时,它都会抛出一个我无法调试的异常。错误显示“Final.exe中0x00D01367处的未处理异常:0xC0000005:访问冲突写入位置0x00000000”。我无法使用s[i] = value;
并且应该使用s.push_back(value);
代替吗?我之前使用过前者没有任何问题,所以我无法弄清楚为什么我现在收到错误。
#include <iostream>
#include <vector>
#include <list>
#include <cassert>
using namespace std;
typedef unsigned int uint;
uint partition(uint low, uint high, vector<double> & s)
{
uint i; //first index for partitioning
uint j; //second index for partitioning
uint pivotpoint; //index of the partition
double pivotvalue; //value at the pivot
double swapvalue; //placeholder variable for the swap
pivotvalue = s[low];
j = low;
for (i = (low+1); i<=high; i++)
{
if (s[i] < pivotvalue)
{
j++;
swapvalue = s[i];
s[i] = s[j];
s[j] = swapvalue;
}
}
pivotpoint = j;
swapvalue = s[low];
s[low] = s[pivotpoint];
s[pivotpoint] = swapvalue;
return pivotpoint;
}
void quicksort(uint low, uint high, vector<double> & s)
{
uint pivotpoint;
if(high>low)
{
pivotpoint = partition(low,high,s);
if(pivotpoint != 0)
{
quicksort(low, pivotpoint-1, s);
}
if(pivotpoint != high)
{
quicksort(pivotpoint+1,high, s);
}
}
}
int main( /*int argc, char* argv[] */)
{/*
if( argc != 2 )
{
cout << "Usage: ./filename.txt" << endl;
cout << "filename.txt should be a file with the items to be sorted" << endl;
exit( 2 );
}
assert(argc == 2)
{
}
*/
vector<double> s;
s[0] = 1.1;
s[1] = 2.4;
s[2] = 7.1;
s[3] = 5.4;
s[4] = 2.5;
s[5] = 1.2;
s[6] = 0.9;
quicksort(0,s.size(),s);
for(uint i = 0; i<s.size(); i++)
{cout << s[i] << endl;}
return 0;
}
答案 0 :(得分:4)
一个直接的问题是矢量初始化:
vector<double> s;
s[0] = 1.1;
s[1] = 2.4;
s[2] = 7.1;
s[3] = 5.4;
s[4] = 2.5;
s[5] = 1.2;
s[6] = 0.9;
由于向量的大小为零,所有上述s[]
赋值都超出范围。
最简单的修复方法可能是将第一行更改为:
vector<double> s(7); // set the size at construction
在C ++ 11中,您可以用以下内容替换整个内容:
vector<double> s{1.1, 2.4, 7.1, 5.4, 2.5, 1.2, 0.9};