【问题标题】:sorting and grouping of an obj arrayobj数组的排序和分组
【发布时间】:2013-11-17 19:39:55
【问题描述】:

把它想象成一个对象数组。对象由类型和分数组成。 假设我需要相应地对它们进行排序,输入 a 或 b,给出优先级,然后按降序排列从 0 -100 的分数。

 [0]   [1]   [2]   [3]    [4]     [5]    [6]
----------------------------------------------
|a   | b   | a   |   a |    b  |    b  |  a  |
|50  | 90  | 30  |   80|    20 |   30  |  60 |
----------------------------------------------

排序后会是这个样子。

[0]   [1]   [2]   [3]    [4]     [5]    [6]
----------------------------------------------
| a  | a   | a   |   a |   b   |    b  |  b  |
| 80 | 60  | 50  | 30  |  90   |  30   | 20  |
----------------------------------------------

只允许使用 if else 语句,循环,例如(for,do while,while),代码量最少。我唯一想到的是通过将 a 组合在一起对数组进行排序,然后按 desc 排序进行排序。使用嵌套 for 循环,带有 if else 语句

char first, second;

for (int i = 0; i < count; i++)
{ 
  first = array[i].getType();
  for (int j = 0; j < count; j++)
    {
        second = array[j].getType();
        if ((first.compare('a') == 0) && (second.compare('a') != 0) ||
              (first.compare('a') != 0)  && (second.compare('a') == 0))
        {
             Obj temp = array[i];
             array[i] = array[j];
     array[j] = temp; 
         }
     }
 }

后跟按 desc 顺序排序。我确信那里有更好的解决方案。任何人都可以分享您如何解决这个问题?

【问题讨论】:

  • 为什么不能使用标准库?它的存在是有原因的。
  • 查看en.wikipedia.org/wiki/Bubblesorten.wikipedia.org/wiki/Quicksort 获取一些排序算法的伪代码。冒泡排序更容易,快速排序更好。
  • std::sort(std::begin(array), std::end(array), [](const Object&amp; l, const Object&amp; r){ return l.type == r.type ? l.score &lt; r.score : l.type &lt; r.type;});

标签: c++


【解决方案1】:

在我看来,最简单、最简洁的方法是为您的类型定义一个比较运算符。

struct object
{
  char type;
  int score;
}

bool operator<(object const& l, object const& r)
{
  return (l.type == r.type) ? l.score < r.score : r.type < l.type;
}

您可以将它与来自 STL 的 std::sort 算法一起使用:

vector<object> objs;
std::sort(objs.begin(), objs.end());

与 C 样式的数组相同。

如果不允许您使用std::sort(如在某些作业中),那么您可以实现任何排序算法(冒泡排序、快速排序等),只需将两个objects 与运算符<.>进行比较

// dummy example
for(int i = 0; i < count; ++i)
{
   for(int j = 0; j < count; ++j)
   {
      auto second = objs[j];
      if(!(objs[i] < objs[j]))
         std::swap(objs[i], objs[j]);
   }
}

【讨论】:

  • 在不定义其他 5 个比较运算符的情况下为类型定义 operator&lt; 很少(可能永远不会)有意义。如果类型 should 是可比较的,则定义所有 6,否则如果这只是用于排序,在这种情况下是,为 sort 创建一个比较器,而不是混淆你可以用类型做什么,不一致。
猜你喜欢
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
  • 2021-10-31
  • 2020-08-30
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多