使用std :: sort与原始指针数组? [关闭]

问题描述 投票:-4回答:1

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

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和指针数组有关。我用更接近我的代码替换了示例代码。弄清楚我有一个错字。在比较器的所有情况下我都没有返回。

c++ lambda
1个回答
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() {}
© www.soinside.com 2019 - 2024. All rights reserved.