用lambda创建unordered_set

LxL*_*LxL 7 c++ hash lambda unordered-set c++11

我怎么unordered_set用lambda做?(我知道如何使用用户定义的哈希结构和它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;
}
Run Code Online (Sandbox Code Playgroud)

它给我几个!错误数量(实时):

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

gcc 4.8编译该代码也很奇怪!(现场)

Pra*_*ian 10

std::function您的代码中不需要抽象.只需通过decltypefor 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);
Run Code Online (Sandbox Code Playgroud)

而在你只是进行了结构的两个元素比较中的地方,我觉得它更容易使用std::tie,而不是

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

上面的代码在gcc和clang上编译,但在VS2013上没有,因为这个bug.VS标准库实现尝试默认在某处构造lambda类型,这将失败,因为删除了默认构造函数.std::function可以用作VS2013的解决方法,但我坚持struct用重载定义一个operator().