【问题标题】:Sorting elements in struct结构中的元素排序
【发布时间】:2013-07-11 14:51:47
【问题描述】:

我有一个结构:

struct points{
int i;
int x;
int y;
};

我制作了一个结构数组并将元素放入其中。 i 元素表示某个点的标签。假设我有 1 2 3 作为数组中的输入。 1 对应于点 (2, 3) 的标签。然后我尝试对 x 元素进行排序:

for (a=0; a < i; a++){
                    for (b = 0; b < i; b++){
                        if (pt[b].x > pt[b+1].x){
                        temp1 = pt[b].x;
                        pt[b].x = pt[b+1].x;
                        pt[b+1].x = temp1;
                        }                       
                    }                               
                }

排序正确。现在,当我打印 i(标签)时,它在排序时与 x 元素不对应。简而言之,只有 x 元素移动了。我想让 i 和 y 在排序时与 x 一起移动。我该怎么办?

【问题讨论】:

  • 你只是在改变 x 的值,而不是 y 或 i 的值

标签: c sorting struct


【解决方案1】:

您需要交换所有数据,而不是仅仅交换 x,以便对整个结构数组进行排序。

为清楚起见,您可以使用单独的函数来执行此操作:

void swap_points(struct points *pa, struct points *pb)
{
  const struct points tmp = *pa;
  *pa = *pb;
  *pb = tmp;
}

然后调用它而不是排序中最内层的三行代码。

您真的应该使用qsort() 来执行此操作,它要简单得多:

static int compare_points(const void *va, const void *vb)
{
  const struct points *pa = va, *pb = vb;

  return pa->i < pb->i ? -1 : pa->i > pb->i;
}

qsort(pt, i, sizeof pt[0], compare_points);

【讨论】:

    【解决方案2】:

    您实际上是在对数组进行排序,但只是 i 的值,而不是整个结构!

    你会想在这里使用 C 的 qsort

    #include <stdlib.h>
    #include <stdio.h>
    
    struct points
    {
        int i;
        int x;
        int y;
    };
    
    int compare(const struct points *a, const struct points *b)
    {
        if (a->i < b->i) return -1;
        if (a->i == b->i) return 0;
        if (a->i > b->i) return 1;
    }
    
    int main(void)
    {
        int i;
        struct points p[3] = { { 4, 2, 1 }, { 1, 3, 5 }, { 2, 8, 1 } };
    
        qsort(p, 3, sizeof(struct points), 
            (int (*)(const void*, const void*)) compare);
    
        printf("{ ");   
        for (i=0; i<3; ++i) 
        {
            printf("{ %d, %d, %d }", p[i].i, p[i].x, p[i].y);
            if (i < 2) printf(", ");
        }
        printf(" }\n");
    }
    

    http://www.cplusplus.com/reference/cstdlib/qsort/

    【讨论】:

    • 谢谢!后续问题。排序后,如果 x 元素中存在关系,我如何以增加 y 值对其进行排序?
    • 您只需为此修改compare() 函数。我认为您首先要将其从按i 排序更改为按x 排序,然后编辑a-&gt;x == b-&gt;x 的案例以考虑y,即添加三个ifs 的嵌套块(就像你有此处)在此声明中。
    【解决方案3】:

    你也必须复制结构中的其他元素。 我想你写一个替换元素值的函数,像这样:

    void copyPoints(point1* a, point2* b)
    {
        int temp = a->i;
        a->i = b->i;
        b->i = temp;
        temp = a->x;
        a->x = b->x;
        b->x = temp;
        temp = a->y;
        a->y = b->y;
        b->y = temp;
    }
    

    然后像这样修改代码:

    for (a=0; a < i; a++)
    {
        for (b = 0; b < i; b++)
        {
            if (pt[b].x > pt[b+1].x)
                copyPoints(&(pt[b]),&(pt[b+1]));  
        }                               
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      • 2014-01-13
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      相关资源
      最近更新 更多