【问题标题】:Sort structs with many numbers inside对内部包含许多数字的结构进行排序
【发布时间】:2013-12-27 20:23:51
【问题描述】:

我想对一个结构数组进行排序,其中每个结构都有一个数组。我想为排序创建我的自定义 compare() 函数,但还没有:

struct box{
    int dims[6];
} boxArray[32];

所以,有 32 个盒子,每个盒子有 6 个维度。

例如,

box1 具有以下尺寸:

1 2 5 10 20 30

盒子2:

1 2 3 4 5 6 9

我希望 box2 排在 box1 之前,因为在前两个维度中它们是相等的,但在下一个维度中,框 2 更小。

我的想法是使用排序

(boxArray,boxArray+32,customCmpBoxes)

在自定义函数内部,递归比较直到一个更小(或不是),但我无法让它工作。

【问题讨论】:

  • 这是正确的方法 - 到目前为止,您为 customCmpBoxes 功能尝试了什么?
  • 您没有显示比较功能。您不会将指针传递给比较函数,然后将它们与某种循环进行比较吗?递归似乎过于复杂。

标签: c++ sorting compare


【解决方案1】:
bool customCmpBoxes(const box& left, const box& right) {
  return std::lexicographical_compare(
    left.dims, left.dims + sizeof(left.dims)/sizeof(left.dims[0]),
    right.dims, right.dims + sizeof(right.dims)/sizeof(right.dims[0]));
}

【讨论】:

    猜你喜欢
    • 2011-06-03
    • 2023-02-03
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多