c++11 unordered_set 哈希函数语法错误

c++11 unordered_set with hash function syntax error

我有这个代码:

#include<unordered_set>
using namespace std;
struct E{
    size_t distance;
    bool operator>(const E& e)const{
        return distance > e.distance;
    }
    bool operator<(const E& e)const{
        return distance < e.distance;
    }
};
int main(){
    unordered_set<E> s;
    return 0;
}

当我用 g++ 7.3 编译它时,出现了很多错误:

g++ m.cpp -std=c++11
In file included from /usr/include/c++/7/bits/hashtable.h:35:0,
                from /usr/include/c++/7/unordered_set:47,
                from m.cpp:1:
/usr/include/c++/7/bits/hashtable_policy.h: In instantiation of ‘struct std::__detail::__is_noexcept_hash<E, std::hash<E> >’:
/usr/include/c++/7/type_traits:143:12:   required from ‘struct std::__and_<std::__is_fast_hash<std::hash<E> >, std::__detail::__is_noexcept_hash<E, std::hash<E> > >’
/usr/include/c++/7/type_traits:154:31:   required from ‘struct std::__not_<std::__and_<std::__is_fast_hash<std::hash<E> >, std::__detail::__is_noexcept_hash<E, std::hash<E> > > >’
/usr/include/c++/7/bits/unordered_set.h:98:63:   required from ‘class std::unordered_set<E>’
m.cpp:13:22:   required from here
/usr/include/c++/7/bits/hashtable_policy.h:87:34: error: no match for call to ‘(const std::hash<E>) (const E&)’
noexcept(declval<const _Hash&>()(declval<const _Key&>()))>
        ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/7/bits/move.h:54:0,
                from /usr/include/c++/7/bits/stl_pair.h:59,
                from /usr/include/c++/7/utility:70,
                from /usr/include/c++/7/unordered_set:38,
                from m.cpp:1:
/usr/include/c++/7/type_traits: In instantiation of ‘struct std::__not_<std::__and_<std::__is_fast_hash<std::hash<E> >, std::__detail::__is_noexcept_hash<E, std::hash<E> > > >’:
/usr/include/c++/7/bits/unordered_set.h:98:63:   required from ‘class std::unordered_set<E>’
m.cpp:13:22:   required from here
/usr/include/c++/7/type_traits:154:31: error: ‘value’ is not a member of ‘std::__and_<std::__is_fast_hash<std::hash<E> >, std::__detail::__is_noexcept_hash<E, std::hash<E> > >’
    : public __bool_constant<!bool(_Pp::value)>

我哪里错了,如何解决?

std::unordered_set 不需要 operator<operator> 作为您提供的类型 E。它确实需要您未提供的散列函数或类似函数的对象(或默认为 std::hash<E>),以及您也未提供的 operator==

如果您无法提供 std::hash<E>,您可以切换到 std::map,但速度会较慢。