使用std :: sort与原始指针数组?

时间:2019-04-25 20:30:23

标签: c++ lambda

假设您有一些较旧的代码和数据结构:

struct TEST
{
   int a;
   int b;
};

TEST *items[9]; // Points to an array of TEST*

现在我要对这些对象进行排序。旧代码使用QSort,但我想使用std :: sort。会是什么样?

我尝试过类似的事情:

typedef std::function<bool(const TEST *, const TEST*)> TestCompareType;
TEST **items;
std::sort(items, items+size, 
    [](const TEST *p1, const TEST *p2) 
    {
        if(p1->a == p2->a)
        {
            return p1->b < p2->b;
        }
        else 
        { 
            // Ooops! Forgot to put "return here"
            p1->a < p2->a;

            // This would fix it
            // return p1->a < p2->a;
        }
    });

但是我崩溃了,说“表达式:无效的比较器”

有什么想法吗?

更新:我完全认为错误与使用std :: sort和指针数组有关是完全错误的。我用更接近我的代码替换了示例代码。弄清楚我有错字。在比较器的所有情况下,我都没有得到回报。

1 个答案:

答案 0 :(得分:3)

使用时

struct
{
   int a;
   int b;
} TEST;

您将TEST定义为匿名struct类型的变量。

然后您继续使用TEST,就好像它是一种类型。

TEST **items;

更改TEST的定义,使其成为一种类型。

struct TEST
{
   int a;
   int b;
};

这是一个演示程序,可以成功构建,但是没有做任何有用的事情。

#include <algorithm>
#include <cstddef>

struct TEST
{
   int a;
   int b;
};

void sortStuff(TEST** items, size_t size)
{
   std::sort(items, items+size,
             [](const TEST *p1, const TEST *p2) { return p1->a < p2->a; });
}

int main() {}