【问题标题】:Error: expression cannot be used as a function. How to remove this?错误:表达式不能用作函数。如何删除这个?
【发布时间】:2023-12-29 19:30:01
【问题描述】:

我正在使用这个结构

    struct box
    {
        int h,w,d;
    };
    int compare (const void *a, const void * b)
    {
        return  ((*(box *)b).d * (*(box *)b).w) – ((*(box *)a).d * (*(box *)a).w); // error is showing in this line
    }
    box rot[3*n];
    qsort (rot, n, sizeof(rot[0]), compare);

我正在尝试 qsort 但显示错误表达式不能用作函数中

【问题讨论】:

  • 长线中间的那个字符 不是减号,而是一个破折号。一旦修复,您的代码compiles for me
  • 如果您编写了可读的代码,您可能会更容易找出错误。将所有内容浓缩为一个陈述对您没有任何好处。
  • @Igor Tandetnik 谢谢它也对我有用,但你是如何检测到的?
  • how you detect that? 编译器told me.
  • 只需使用std::sort。它快了很多

标签: c++ compare qsort


【解决方案1】:

返回行中的减号运算符有问题,应该是 - 而不是

定义数组 rot 时的另一个问题,它应该包含类型为 struct box 而不是 box 的元素,因为结构中有 NO typedef阻止

因此,您有两种使其工作的可能性,或者您为结构box 添加标签box

typedef struct box
{
    int h,w,d;
} box;

或者只是在数组rot 的定义和类似的比较函数中添加单词struct(在每个box 单词之前):

int compare (const void *a, const void * b)
{
    return  ((*(struct box *)b).d * (*(struct box *)b).w) - ((*(struct box *)a).d * (*(struct box *)a).w);
}

struct box rot[3*n];

【讨论】:

  • 这是 C++,typedef 不是必需的。
最近更新 更多