[英]lambda function doesn't work in priority_queue in c++ (when using [&])
当我在做Leetcode.com时,无法编译以下代码。
auto cmp=[&](pair<int,int> a, pair<int,int> b){return heightMap[a.first]
[a.second]<heightMap[b.first][b.second];};
priority_queue<pair<int,int>,vector<pair<int,int>>,decltype(cmp)> pq;
我使用时效果很好
auto cmp=[](...){return true;}.
但是我必须用
auto cmp=[&](...){...}
因为我需要在函数中访问heightMap。
我不知道为什么不能编译
我假设您正在块作用域内(即在函数内部)工作。
对于[&]
和[]
情况,正确的代码应为:
priority_queue<pair<int,int>,vector<pair<int,int>>, decltype(cmp)> pq(cmp);
// ^^^^^
您可以在cppreference示例中看到这一点。
如果您考虑一下,仅带有decltype(cmp)
的pq
的定义就不会知道任何局部变量-附件仅在cmp
的实际创建中形成。
原因是priority_queue
的默认构造函数为(C ++ 17 [priqueue.cons]):
explicit priority_queue(const Compare& x = Compare(), Container&& y = Container());
如您所见,这涉及默认构造Compare
类型的对象。 在C ++ 20之前, lambdas不是默认可构造的 。
P0624添加了默认的无状态lambda构造,它并没有完全融入C ++ 17,但现在出现在C ++ 20草案中。
从技术上讲,C ++ 17编译器甚至应拒绝[]
版本; 但是似乎有些编译器已经在C ++ 20支持上抢占了先机。
我注意到,当实际上没有捕获任何变量时,clang ++ 6.0.0实际上允许默认构造为指定为[&]
的lambda。 而P0624的措辞则表明该案应予驳回。 也许这将在C ++ 20完成之前再次改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.