我有一个表存储在连续内存中。排序后,它必须保持该格式。

例如:

int table[5][3] = {
    { 60, 5, 10 },
    { 0, 200, 15 },
    { 55, 50, 365 },
    { 4, 7, 78 },
    { 555, 8, 11 },
};

除了更大以外(最大的大小(以字节为单位)约为27 KB)。每个单元格始终是一个int32,并且所有行都具有相同数量的列。

假设我要根据第一列对其进行排序,因此结果必须等于:
    { 0, 200, 15 },
    { 4, 7, 78 },
    { 55, 50, 365 },
    { 60, 5, 10 },
    { 555, 8, 11 },

最好的方法是什么?我想有比将其转换为std::list,调用sort()并转换回更好的方法。

另外,最好只在C++中内置一些我必须调用某些函数的东西。

最佳答案

std::sort很难做到这一点,因为数组是不可分配的。

但是,std::qsort可以做到:

int cmp_first_column(const void *lhs_, const void *rhs_) {
    // optimize this to taste
    const int *lhs = static_cast<const int*>(lhs_);
    const int *rhs = static_cast<const int*>(rhs_);
    if (lhs[0] < rhs[0]) return -1;
    if (lhs[0] > rhs[0]) return 1;
    return 0;
}

std::qsort(table, 5, 3*sizeof(int), cmp_first_colum);

好的,因此std::qsort不能从模板内联优化中受益,但是它可以完成工作,至少您不需要分配大量内存并进行不必要的复制。

您可以改用int[3]作为数据成员的结构数组替换int[3]数组。这将是可分配的,您可以正常使用std::sort。取决于您编写了多少依赖当前类型的其他代码,以及是否可以破坏该代码使用的接口(interface)。

关于c++ - 我有一个表存储在内存中。如何基于列对其进行排序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5136724/

10-08 21:59
查看更多