Apr 27, 2012 at 8:58am UTC
I am getting this error msg when I debug it.
But sometimes run fine but sometimes dont.
Debug Assertion Failed
C:\.......
Line: 932
Expression: vector subscript out of range.
I cant find the mistake please help.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
#include "sort.h"
using namespace std;
int main()
{
vector <int> data(20);
srand(time(0));
for(int i=0; i< 20; i++)
data[i] = (rand() % 200);
sort vec(data);
system("pause");
return 0;
}
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
#ifndef SORT_H
#define SORT_H
class sort
{
public:
sort(vector<int> vec);
void display();
void quickSortHelper(int, int);
int midPoint(int, int, int);
private:
vector <int> vec ;
};
#endif
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
#include "sort.h"
using namespace std;
sort::sort(vector<int> vec)
:vec(vec)
{
cout << "Initial vector values are: " << endl;
display();
quickSortHelper(0, 19);
cout << "The sorted vector values are: " << endl;
display();
//fillVec();
}
void sort::display()
{
for(int i=0; i< 20; i++)
cout << vec[i] << " ";
cout << endl << endl;
}
void sort::quickSortHelper(int startIndex, int endIndex)
{
int pivot = vec[startIndex];
int splitPoint;
if(endIndex > startIndex)
{
splitPoint = midPoint(pivot, startIndex, endIndex);
vec[splitPoint] = pivot;
quickSortHelper( startIndex, splitPoint-1);
quickSortHelper( splitPoint+1, endIndex);
}
}
int sort::midPoint(int pivot, int startIndex, int endIndex)
{
int leftBoundary = startIndex;
int rightBoundary = endIndex;
while(leftBoundary < rightBoundary)
{
while( pivot < vec[rightBoundary]
&& rightBoundary > leftBoundary)
{
rightBoundary--;
}
swap(vec[leftBoundary], vec[rightBoundary]);
while( pivot >= vec[leftBoundary]
&& leftBoundary < rightBoundary)
{
leftBoundary++;
}
swap(vec[rightBoundary], vec[leftBoundary]);
}
return leftBoundary;
}
Apr 27, 2012 at 10:04am UTC
If I had to guess, I'd say you're accessing elements outside your vector's range (so an index < 0 or > 19). The implementation of std::vector does bound checking for the []-operator while in debug mode.