c++ - 使用 lambda 创建 unordered_set

标签 c++ c++11 hash lambda unordered-set

如何使用 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 抽象。只需通过 decltypeunordered_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/

相关文章:

c++ - 递归算法

c++ - 根据枚举成员的值特化模板

c++11 - 魔法静力学的发布线程安全吗?

c++ - 如何在最后一个节点中使奇数偶数LinkedList因子?

c++ - 在 C++ 中,迭代器失效规则是否也适用于所有标准容器的指针?

c++ - 运行时检查失败 #2 C/C++

c++ - 在 C++ 中拆分 const char*

C# MD5 哈希需要匹配 PHP MD5 哈希(带盐)

algorithm - 两种选择哈希中的预期碰撞对

php - 在 sql 比较查询之前将长字符串转换为短哈希 - 提高性能?