编写要与unordered_map一起使用的类。

时间:2011-07-30 20:09:37

标签: c++ boost

我想使用boost map,文档说我需要一个相等的函数和一个哈希函数。我认为理解他们应该做什么,但因为我找不到任何例子我不知道该怎么做所以我正在寻找一个简单的例子,比如一个成员x,y或者接近的点类。

修改:终于搞定了。希望我没有浪费这么多时间。无论如何,谢谢你们。

#include <boost/functional/hash.hpp>
#include <boost/unordered_map.hpp>
#include <boost/foreach.hpp>
#include <iostream>

namespace test { // class whose source i can't edit
    class point
    {
    public:
        float x;
        float y;
        point() : x(0), y(0) {}
        point(int x, int y) : x(x), y(y) {}
        point(float x, float y) : x(x), y(y) {}
        point(double x, double y) : x((float) x), y((float) y) {}

        bool operator==(point const& other) const
        {
            return x == other.x && y == other.y;
        }
    };
}

namespace test { // my source file
    std::size_t hash_value(point const &p) {
        boost::hash<int> hasher;
        return hasher(p.x) + hasher(p.y);
    }
} 

int main() {
    boost::unordered_map<test::point, std::string> myMap;
    test::point p1(1, 2);
    myMap[p1] = "1"; //now it works
    std::cout << myMap[p1] << std::endl;
    return 0;
}

2 个答案:

答案 0 :(得分:3)

平等和散列不是很难定义。平等:

class Point {
    int x, y;
    bool operator==(const Point& p) {
        return (x == p.x && y == p.y);
    }
};

散列往往涉及专门化一个函数或类。

template<> class boost::hash<Point> {
public:
    size_t operator()(const Point& p) {
        return boost::hash<int>(p.x) + boost::hash<int>(p.y);
    }
};

您可能需要阅读hash_map实现的细节以获取详细信息,并且您可能还需要定义不同的哈希算法。

答案 1 :(得分:3)

这是boost documentation ...

class point
{
    int x;
    int y;
public:
    point() : x(0), y(0) {}
    point(int x, int y) : x(x), y(y) {}

    bool operator==(point const& other) const
    {
        return x == other.x && y == other.y;
    }
};

class point
{
    ...

    friend std::size_t hash_value(point const& p)
    {
        std::size_t seed = 0;
        boost::hash_combine(seed, p.x);
        boost::hash_combine(seed, p.y);

        return seed;
    }

    ...
};
相关问题