1

I was wondering why std::map allows the node to be user-defined type but std::unordered_set doesn't? As far as I understand, I assumed std::map is implemented using a binary tree and std::unordered_set is a hashtable.

For instance

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

However, the same doesn't compile on std::unordered_set

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

which is weird to me since I consider foo is the value from the < key,value > in the hastable as well, and they are all template parameter of type Class K in the declaration. Thank you very much

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

I guess from the printout, the reason is that the user defined type is not hashable by the stl::hash function? Thanks

4

1 回答 1

2

“std::unordered_set 的声明遮蔽了一个参数”

这和套路无关。

您将其命名为与函数参数相同的名称。

重命名它。

不过,请确保您的值类型具有关联的哈希和相等函数;回想一下,对于您的地图,您的类型需要一个排序功能。

于 2013-11-06T23:10:36.920 回答