如何使用 lambda 生成 unordered_set
? (我知道如何使用用户定义的哈希结构和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;
}
它给我几个!错误数 ( live ):
请注意,我为返回 std::function
(equalFunc
,hashFunc
) 创建了一个 lambda,因为它似乎在 unordered_set 中
某些函数正在尝试复制该 lambda 的返回类型!
gcc 4.8 编译该代码也很奇怪! ( live )
最佳答案
您的代码中不需要 std::function
抽象。只需通过 decltype
为 unordered_set
的模板参数直接获取 lambda 类型
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);
};
上面的代码在 gcc 和 clang 上都可以编译,但由于 this bug 而不能在 VS2013 上编译。 . VS 标准库实现试图在某处默认构造 lambda 类型,这将失败,因为默认构造函数被删除。 std::function
可用作 VS2013 的解决方法,但我会坚持使用重载的 operator()
定义 struct
.
关于c++ - 使用 lambda 创建 unordered_set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25454806/