使用结构的两个字段比较 qsort 的函数? [英] Compare function for qsort using two fields of a structure?

查看:43
本文介绍了使用结构的两个字段比较 qsort 的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个结构:

     struct product 
 {
    char name[30]; 
    float price;
 };

我想先使用 qsort 按价格对其进行排序,如果价格相等,则按名称排序.我是如何想到编写比较函数的:

I want to sort it using qsort first by price, and if the prices are equal, by name. How I thought of writing the compare function:

    int compare(const void *a, const void *b )
{
    int comp =  a.price - b.price;

    if (comp < 0 )
    return 1
    if (comp > 0 )
        return 0;


    comp = strcmp(a.name, b.name);

   if ( comp  < 0 )
       return 1;
   else
   if ( comp > 0 ) 
       return 0;

}

由于我只对 qsort 使用了常用的比较函数,所以我不知道该怎么做.根据给出的错误,我认为我访问的字段不正确,所以请您指出我在编写比较函数时的错误吗?

Since I have only used the usual compare function for qsort, I don't know how to go about this. I think that I'm accessing the fields incorrectly, based on the errors given, so could you please point out my mistakes writing the compare function?

推荐答案

您编写的代码有几个语法错误,而且您的比较函数也不能完全按照您的要求执行.引用 qsort 的联机帮助页:

Your code as written has several syntax errors, and also your comparison function doesn't do quite what you want. Quoting from the manpage for qsort:

比较函数必须返回一个小于、等于或的整数如果第一个参数被认为是re​​spec - 大于零小于、等于或大于第二个.如果两个内存bers 比较相等,它们在排序数组中的顺序是不确定的.

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respec‐ tively less than, equal to, or greater than the second. If two mem‐ bers compare as equal, their order in the sorted array is undefined.

考虑以下代码:

#include <stdlib.h>
#include <string.h>

struct product {
    char name[30]; 
    float price;
};

int compare(const void *a, const void *b) {

  const struct product *x = a;   // void* can be assigned to any other pointer type
  const struct product *y = b;

  int comp =  x->price - y->price;

  if (comp < 0)
    return -1;

  if (comp > 0)
    return 1;

  comp = strcmp(x->name, y->name);

  return comp;
}

如果要反转排序顺序,请在适当的位置取消 comp.

If you want to reverse the sort order, negate comp at the appropriate place.

正如其他人提到的,这是 C 代码,而不是惯用的 C++.

As others have mentioned, this is C code, and is not idiomatic C++.

这篇关于使用结构的两个字段比较 qsort 的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆