set_intersection可以和C ++中的hash_set一起使用吗?

时间:2010-03-12 20:03:19

标签: c++ stl set intersection hashset

我正在计算集合的交集,并集和差异。 我有一个我的集类型的typedef:

typedef set<node_type> node_set;

替换为

typedef hash_set<node_type> node_set;

结果不同。这是一个复杂的程序,在我开始调试之前 - 我做得对吗?当我使用这样的函数时:

set_intersection(v_higher.begin(), v_higher.end(), neighbors[w].begin(), neighbors[w].end(), 
            insert_iterator<node_set>(tmp1, tmp1.begin()));
  • 它们应该与set和hash_set无缝协作吗?

3 个答案:

答案 0 :(得分:5)

我不这么认为。

One of the pre-condition of set_intersection是:

    根据{{​​1}},
  • [first1, last1) 按升序排序。也就是说,对于operator<中的每对迭代器ij[first1, last1)位于i之前,j为假。

*j < *i(和hash_set)是无序的,因此无法满足有序条件。

请参阅tr1::unordered_set union and intersection了解如何与unordered_set进行交叉。

答案 1 :(得分:1)

我打算不行。请记住hash_set不是标准的C ++,永远不会是,它是一个不再受支持的旧版扩展。较新的“哈希映射”称为unordered_setunordered_map,可在TR1,Boost和C ++ 0x中使用。

它是否为set_intersection需要对输入数据进行排序。相反,哈希映射如此之快的原因是它放弃了排序。这显然在名称unordered_set下更为明显。所以前提条件无法可靠地实现。

答案 2 :(得分:0)

不,您不能使用set_intersection,因为set_intersection要求对这两个集合进行排序(使用相同的顺序)。散列集不以任何方式排序。在C ++ 0x中,它们实际上将被称为unordered_set