带矢量对象C ++的Quicksort函数 [英] Quicksort function with vector object C++

查看:46
本文介绍了带矢量对象C ++的Quicksort函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将此函数转换为使用矢量对象而不是整数数组.向量对象如下所示:

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;

Heltal类包含一个名为heltal的私有整数.

The Heltal class contains a private integer named heltal.

如何使用下面的函数对htal向量进行排序?

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::sort from <algorithm>. This will pretty much be guaranteed to be faster and more optimal in almost every case. Then you just have:

#include <algorithm>
...
std::vector<Heltal *> htal;
...
// sort by pointer value
std::sort(htal.begin(), htal.end());

如果要按对象值而不是指针值排序,请使用 std :: vector< Heltal> 而不是 std :: vector< Heltal *> (几乎肯定是您应该做的事情),或者将比较函数传递给std :: sort.

If you want to sort by object value rather than pointer value, either use std::vector<Heltal> instead of std::vector<Heltal *> (which is almost certainly what you should be doing anyway), or pass a comparison function to std::sort.

为此使用C ++ 11 lambda的示例:

Example using C++11 lambda for this:

std::sort(htal.begin(), htal.end(), [](Heltal *a, Heltal *b) { return *a < *b; }); 

这篇关于带矢量对象C ++的Quicksort函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆