【问题标题】:How can I sort the array of class?如何对类数组进行排序?
【发布时间】:2019-11-09 19:17:55
【问题描述】:

我已经使类具有二维数组 (4 x 4) 和二维数组中的最大值,如下所示:

class B {
public:
    int shape[4][4] = { 0 };
    int maxh = 0;

    B() {};

    void record(int module[4][4]) {
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                shape[i][j] = module[i][j];
                if (shape[i][j] > maxh) { maxh = shape[i][j]; }
            }
        }
    }
};

如果有一个类'B'数组,

B b_arr = new B[30000];

如何按最大值对类对象数组进行排序?

我尝试像下面的代码那样对数组进行排序,但出现堆栈溢出错误。

int partition(B arr[], int p, int r) {
    int i = p - 1;
    for (int j = p; j < r; j++) {
        int cri = arr[r].maxh;
        if (arr[j].maxh < cri) {
            i++;
            B tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }
    }
    B tmp = arr[i + 1];
    arr[i + 1] = arr[r];
    arr[r] = tmp;
    return i + 1;
}


void quickSort(B arr[], int p, int r) {

    if (p < r) {
        int q = partition(arr, p, r);
        quickSort(arr, p, q - 1);
        quickSort(arr, q + 1, r);
    }
}

【问题讨论】:

  • 你为什么不使用 std::sort ?

标签: c++


【解决方案1】:

您可以为std::sort() 定义比较器:

请看下面的原型:

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );

例如你可以这样做:

std::sort(
    /*std::begin(b_arr)*/b_arr,
    /*std::end(b_arr)*/b_arr+30000,
    [](const B& left, const B& right){
        return left.maxh < right.maxh;
    }
);

请注意,std::begin()std::end() 不适用于指向动态数组的指针。在这种情况下,您必须通过添加大小来指定范围。我建议改用std::vectorstd::array

【讨论】:

【解决方案2】:

如果你为类对象定义了一个比较器函数,你可以使用std::qsort

int bArrCompare(const void* a, const void* b) {
    const B* pa = reinterpret_cast<const B*>(a);
    const B* pb = reinterpret_cast<const B*>(b);
    return (pb->maxh - pa->maxh);
}

int main()
{
    B* b_arr = new B[30000];
    //...
    std::qsort(b_arr, 30000, sizeof(B), bArrCompare);
    //...
    return 0;
}

【讨论】:

  • qsort() 是一个 C 函数。在 C++ 中使用 std::sort()
  • @RemyLebeau std::qsortC++ 中可用 - 它更容易用于“旧式指针”数组。
  • 使用qsort()std::sort() 相比更容易,您可以使用比@987654331 更少的参数将“旧式指针”数组传递给std::sort() @,并且std::sort() 比较器中不需要类型转换。所以使用std::sort()实际上更容易,而且由于没有size参数会出错
猜你喜欢
  • 2013-12-20
  • 2021-02-18
  • 2022-01-20
  • 2021-12-12
  • 1970-01-01
  • 2017-07-03
  • 2014-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多