std :: map和std :: unordered_set中的类类型

时间:2013-11-06 22:57:14

标签: c++

我想知道为什么std :: map允许节点是用户定义的类型但是std :: unordered_set不是? 据我所知,我假设std :: map是使用二叉树实现的,而std :: unordered_set是一个哈希表。

例如

struct foo{
 int a;
 int b;
};

std::map<int,foo> m; //it is allowed, foo is the tree node that is value from the <int,foo> <key,value> pair

但是,同样不能在std :: unordered_set

上编译
std::underedset_set<foo> s //failed, "declaration of std::unordered_set<foo> s shadows a parameter"

这对我来说很奇怪,因为我认为foo是来自&lt;的值。键,值&gt;在hastable中,它们都是声明中类K的模板参数。非常感谢你

template < class Key,                                     // map::key_type
       class T,                                       // map::mapped_type
       class Compare = less<Key>,                     // map::key_compare
       class Alloc = allocator<pair<const Key,T> >    // map::allocator_type
       > class map;

template < class Key,                        // unordered_set::key_type/value_type
       class Hash = hash<Key>,           // unordered_set::hasher
       class Pred = equal_to<Key>,       // unordered_set::key_equal
       class Alloc = allocator<Key>      // unordered_set::allocator_type
       > class unordered_set;

EDIT1:

std::unordered_set<foo> s // failed again for different reason, which was really what I was asking

In file included from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/basic_string.h:3032:0,
                 from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/string:54,
                 from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/random:41,
                 from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/stl_algo.h:67,
                 from /usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/algorithm:63,
                 from ArrayTargetSum.cpp:10:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/functional_hash.h: In instantiation of ‘struct std::hash<foo>’:
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/unordered_set.h:279:11:   required from ‘class std::unordered_set<foo>’
ArrayTargetSum.cpp:70:25:   required from here
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/functional_hash.h:60:7: error: static assertion failed: std::hash is not specialized for this type

我想从打印输出中,原因是用户定义的类型不能通过stl :: hash函数进行清理?感谢

1 个答案:

答案 0 :(得分:2)

  

“std :: unordered_set的声明s遮蔽参数”

这与集合无关。

您给它的名称与函数参数相同。

重命名。

确保您的值类型具有关联的哈希和相等函数;回想一下,对于你的地图, key 类型需要一个订购功能。