【问题标题】:Qsort to sort an array of structs that points to another structQsort 对指向另一个结构的结构数组进行排序
【发布时间】:2013-10-13 07:47:40
【问题描述】:

这是一个我需要帮助的编码问题——首先是使用的结构:

typedef struct node {
   char email[100];
} Node;

typedef struct edge {
   Node *from_email, *to_email;
} Edge;

Node nodes[NODE_ARRAY_SIZE];
Edge edges[EDGE_ARRAY_SIZE];

因此,如您所见,“节点”结构包含一个带有电子邮件的字符数组,“边缘”结构包含指向 2 个不同节点的指针。还有两个数组,一个是Nodes,一个是Edges。

我想对两个数组进行 qsort() - 我已经使用了节点之一:

qsort(nodes, node_size, sizeof(Node), node_cmp_function);
int node_cmp_function(const void *a, const void *b) {
  Node *temp_a = (Node *)a;
  Node *temp_b = (Node *)b;
  return strcmp(temp_a->username, temp_b->username);
}

但我不知道如何对 Edges 数组进行排序 -> 我想在 *from_email 上使用 strcmp 对其进行排序 - 但如果两个被比较的 *from_email 相等,那么我想使用 *to_email 进行排序。

感谢大家的帮助!

【问题讨论】:

  • 你试过什么?你似乎很清楚你需要做什么 - 编写接受边的 qsort 函数,比较 from_email,如果结果相等,比较 to_email。

标签: c arrays sorting struct qsort


【解决方案1】:

如果我正确理解你在做什么,这样的事情可能会起作用(未经测试的代码):

int edge_cmp_function(const void *a, const void *b)
{
    Edge *temp_a = (Edge *)a;
    Edge *temp_b = (Edge *)b;
    int result = 0;

    if ((result = node_cmp_function(temp_a->from_email, temp_b->from_email)) == 0)
    {
        result = node_cmp_function(temp_a->to_email, temp_b->to_email);
    }

    return result;
}

【讨论】:

  • 旁注:不需要(void *) 演员表。
  • 啊哈,工作起来就像一个魅力!我试图使用指针比较,但这很愚蠢——我不敢相信解决方案就在那里。再次感谢!
  • 不客气!谢谢你的注意,Martin R。我已经更新了代码以去除过度明确的演员表!
猜你喜欢
  • 1970-01-01
  • 2021-06-20
  • 1970-01-01
  • 2014-07-04
  • 2016-11-29
  • 2015-12-13
  • 2014-05-21
  • 1970-01-01
相关资源
最近更新 更多