【问题标题】:Is there shortcut when choose elements of struct?选择结构元素时有快捷方式吗?
【发布时间】:2018-12-30 18:49:44
【问题描述】:

我正在尝试对结构数组进行排序。但我想按一个元素排序。例如,我正在使用冒泡排序进行排序。

struct example{
    int num;
    char str[5];
} ex[90];

for(int i = 0; i < 88; i++){
    for(int o = 0; o < 88; o++){
        if(ex[o].num > ex[o + 1].num){
            swap(ex[o].num, ex[o + 1].num);
        }
    }
}

在这段代码中,如何在不再次编写代码的情况下将 ex[o].num 更改为 ex[o].str?

【问题讨论】:

  • 没有。我想对选择的元素进行排序。所以'str'或'num'。我只是问是否有一种方法将 'if(ex[o].num > ex[o + 1].num' 更改为 'if(ex[o].str > ex[o + 1].str)' 而无需写入再次排序代码。

标签: c struct


【解决方案1】:

可以实现比较函数并使用标准库的qsort。除非您想要 stable 排序,否则很难在一般排序方面击败标准库。 qsort 接受compar

compar 参数是一个指向比较函数的指针,它使用两个指向被比较元素的参数调用。如果第一个参数分别被认为小于、等于或大于第二个参数,应用程序应确保该函数返回一个小于、等于或大于 0 的整数。

这样,

#include <stdlib.h> /* EXIT_* qsort */
#include <stdio.h>  /* printf */
#include <string.h> /* strcmp */
#include <assert.h>

struct Example {
    int num;
    char str[5];
} ex[90];

static const size_t ex_size = sizeof ex / sizeof *ex;

static void fill(struct Example *const example) {
    assert(example);
    example->num = rand() / (RAND_MAX / 100.0);
    example->str[0] = rand() / (RAND_MAX / 26.0) + 'A';
    example->str[1] = rand() / (RAND_MAX / 26.0) + 'a';
    example->str[2] = rand() / (RAND_MAX / 26.0) + 'a';
    example->str[3] = rand() / (RAND_MAX / 26.0) + 'a';
    example->str[4] = '\0';
}

static void print(const struct Example *const example) {
    assert(example);
    printf("%d\t\"%s\"\n", example->num, example->str);
}

/* Implements <Example>Comparator. */
static int comp_num(const void *va, const void *vb) {
    const struct Example *a = va, *b = vb;
    return (a->num > b->num) - (a->num < b->num);
}

/* Implements <Example>Comparator. */
static int comp_str(const void *va, const void *vb) {
    const struct Example *a = va, *b = vb;
    return strcmp(a->str, b->str);
}

int main(void) {
    size_t i;
    for(i = 0; i < ex_size; i++) fill(&ex[i]);
    for(i = 0; i < ex_size; i++) print(&ex[i]);
    printf("Sorting by num.\n");
    qsort(ex, ex_size, sizeof *ex, &comp_num);
    for(i = 0; i < ex_size; i++) print(&ex[i]);
    printf("Sorting by str.\n");
    qsort(ex, ex_size, sizeof *ex, &comp_str);
    for(i = 0; i < ex_size; i++) print(&ex[i]);
    return EXIT_SUCCESS;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多