用lambda创建unordered

编程入门 行业动态 更新时间:2024-10-09 08:31:48
本文介绍了用lambda创建unordered_set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何用lambda制作unordered_set? (我知道如何使用用户定义的哈希结构和operator==做到这一点)

How can I make unordered_set with lambda? (I know how to make it with user defined hash struct and operator==)

我当前的代码是:

#include <unordered_set> #include <functional> struct Point { float x; float y; Point() : x(0), y(0) {} }; int main() { auto hash=[](const Point& pt){ return (size_t)(pt.x*100 + pt.y); }; auto hashFunc=[&hash](){ return std::function<size_t(const Point&)> (hash); }; auto equal=[](const Point& pt1, const Point& pt2){ return ((pt1.x == pt2.x) && (pt1.y == pt2.y)); }; auto equalFunc=[&equal](){ return std::function<size_t(const Point&,const Point&)> (equal); }; using PointHash=std::unordered_set<Point,decltype(hashFunc),decltype(equalFunc)>; PointHash Test(10,hashFunc,equalFunc); return 0; }

它给我很少!错误数(实时):

It give me few! number of errors (live):

请注意,我将lambda用作返回std::function(equalFunc,hashFunc)的原因,因为似乎在unordered_set中,某些函数正在尝试复制该lambda的返回类型!

Note that I make a lambda for returning std::function (equalFunc,hashFunc) because it seems that in unordered_set some functions are trying to copy return type of that lambdas !

gcc 4.8编译好的代码也很奇怪! (实时)

Also it's weird that gcc 4.8 compile that code fine ! ( live )

推荐答案

您的代码中无需std::function抽象.只需直接通过decltype获取unordered_set模板参数的lambda类型

There's no need for the std::function abstraction in your code. Just obtain the lambda types directly via decltype for unordered_set's template arguments

auto hash=[](const Point& pt){ return (size_t)(pt.x*100 + pt.y); }; auto equal=[](const Point& pt1, const Point& pt2){ return ((pt1.x == pt2.x) && (pt1.y == pt2.y)); }; using PointHash = std::unordered_set<Point, decltype(hash), decltype(equal)>; PointHash Test(10, hash, equal);

在您只是简单地对两个结构进行逐元素比较的地方,我发现更容易使用std::tie代替

auto equal=[](const Point& pt1, const Point& pt2){ return std::tie(pt1.x, pt1.y) == std::tie(pt2.x, pt2.y); };

由于此错误. VS标准库实现尝试在某处默认构造lambda类型,由于默认构造函数被删除,该类型将失败. std::function可以用作VS2013的解决方法,但我会坚持使用重载的operator()定义struct.

The above code compiles on both gcc and clang, but not on VS2013 because of this bug. The VS standard library implementation tries to default construct the lambda type somewhere, which is going to fail because the default constructor is deleted. std::function can be used as a workaround for VS2013, but I'd stick to defining a struct with an overloaded operator() instead.

更多推荐

用lambda创建unordered

本文发布于:2023-11-29 01:51:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644818.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:lambda   unordered

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!