I’m trying to convert this function to use a vector object instead of an integer array.
The vector object looks like this:
std::vector<Heltal *> htal;
The Heltal class contains a private integer named heltal.
How would I sort the htal vector using the function below?
void Array::Sort(int a[], int first, int last)
{
int low = first;
int high = last;
int x = a[(first+last)/2];
do {
while(a[low] < x) {
low++;
}
while(a[high] > x) {
high--;
}
if(low<=high) {
std::swap(a[low],a[high]);
low++;
high--;
}
} while(low <= high);
if(first < high)
Array::Sort(a,first,high);
if(low < last)
Array::Sort(a,low,last);
}
The correct solution is to ditch your custom sort and use
std::sortfrom<algorithm>. This will pretty much be guaranteed to be faster and more optimal in almost every case. Then you just have:If you want to sort by object value rather than pointer value, either use
std::vector<Heltal>instead ofstd::vector<Heltal *>(which is almost certainly what you should be doing anyway), or pass a comparison function to std::sort.Example using C++11 lambda for this: