如何在VC ++ 2010中使用stdext :: hash_set作为自定义类型?

时间:2012-03-09 06:49:22

标签: c++ visual-c++ stl hashtable containers

我想将stdext::hash_set用于自定义类型。

事实上我意识到该怎么做,但我不确定它是否正确(它是可编辑的,但看起来有点脏)。

代码如下:

// This is my custom type
struct Point 
{
    Point(int _x, int _y, int _z) : x(_x), y(_y), z(_z) {}

    int x, y, z;

    bool operator< (const Point& other) const 
    {
        if (x != other.x) return x < other.x;
        if (y != other.y) return y < other.y;
        return z < other.z;
    }
};

// helper class
struct PointHashCompare {
    // value is copied from MS sources
    static const int bucket_size = 1;

    size_t operator() (const Point& p) const {
      return p.x * 31 * 31 + p.y * 31 + p.z;
    }

    bool operator() (const Point& a, const Point& b) const {
      return a < b;
    }
};

以下变量的声明:

stdext::hash_set<Point, PointHashCompare> hSet;

bucket_size中的PointHashCompare是什么意思? 是否存在解释bucket_size的任何Microsoft文档及其值的建议以及为何需要它?

(我可以假设这与哈希表实现的内部结构有关,但可以使用不同的方法,并且它们也可以在不同的VC ++版本中更改)

我也在考虑切换到std::unordered_set,但现在我想知道如何管理stdext::hash_set

谢谢!

1 个答案:

答案 0 :(得分:1)

  

整数常量bucket_size指定元素的平均数   per&#34; bucket&#34; (散列表条目)容器应该尽量不要   超过。它必须大于零。提供的价值   hash_compare是4。

hash_compare Class页上的更多信息