【发布时间】:2013-11-06 22:57:13
【问题描述】:
我想知道为什么 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 也是 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 函数散列?谢谢
【问题讨论】:
-
尝试将“s”重命名为有意义的名称,例如“s2”。 :)
-
(无序)集合元素的值类型与(无序)映射的键类型要求相同。
-
因为你把 tpyename 卖错了,“underedset_set”?
-
一个是地图,另一个是集合。 “std::map 允许用户自定义节点”是什么意思?
-
一旦你解决了其他 cmets 中指出的问题,我的第一条评论就会开始变得有意义:-)
标签: c++