c++ - 使用 lambda 默认构造的 std::priority_queue

标签 c++ lambda constructor c++20 priority-queue

在定义 std::priority_queue 时,我错误地省略了 compare 参数:

#include <queue>

int main()
{
    constexpr auto cmp{[](int a, int b) { return a > b; }};
    std::priority_queue<int, std::vector<int>, decltype(cmp)> pq;
}

,当我用它实现 Dijkstra 算法时,它编译成功并且工作正常。 然后我发现我在构造pq时只传递了cmp的类型信息。

但是,只有使用 --std=c++20 标志时,代码才会编译。 我浏览了priority_queuecppreference.com 上引用,但找不到任何有关自 C++20 以来发生的更改的通知。

我使用了以下版本的 g++:

g++ (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0

这是自 C++20 以来的预期行为吗?如果是,是什么影响了此更改?

最佳答案

更改发生于 lambdas .

If no captures are specified, the closure type has a defaulted default constructor. Otherwise, it has no default constructor (this includes the case when there is a capture-default, even if it does not actually capture anything). (Since C++20)

在C++20之前,lambda闭包类型不是DefaultConstructible,比较器对象不能在std::priority_queue的默认构造函数中默认构造,然后你必须将 lambda 对象传递给带有比较器对象的 std::priority_queue 构造函数。

constexpr auto cmp{[](int a, int b) { return a > b; }};
std::priority_queue<int, std::vector<int>, decltype(cmp)> pq(cmp);

关于c++ - 使用 lambda 默认构造的 std::priority_queue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69432375/

相关文章:

c++ - 如何使用 std::valarray 来存储/操作连续的二维数组?

c# - 如何在 C# 中为 LambdaExpression 组合 MemberExpression 实例?

java - 如何告诉 Spring 在不提供构造函数参数的情况下实例化选定的 bean?

c++ - 在 WinAPI 中枚举音频适配器

c++ - 在派生构造函数中访问基本成员时出现问题

c# - 如何使用 lambda 指定构造函数参数?

c# - 如何使用 OR/And 运算符组合 N 个表达式树

c++ - 这是一个有效的 Copy Ctor 吗?

arrays - 如何向对象数组添加一个继承的对象? ( swift ,XCode)

c++ - 线程安全队列有问题吗?