在定义 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_queue在 cppreference.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/