Qsort对指向另一个结构的结构数组进行排序

时间:2013-10-13 07:47:40

标签: c arrays sorting struct qsort

这有点像我需要帮助的编码问题 - 首先是使用的结构:

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];

因此,正如您所看到的,“Node”结构包含带有电子邮件的char数组,“Edge”结构包含指向2个不同节点的指针。还有两个阵列,一个是节点,另一个是边缘。

我想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_emails都相等,那么我想使用* to_email进行排序。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

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

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;
}