【问题标题】:c++11 unordered_set with hash function syntax errorc++11 unordered_set 带有哈希函数语法错误
【发布时间】:2018-09-14 21:06:32
【问题描述】:

我有这个代码:

#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)>

我哪里出错了,如何解决?

【问题讨论】:

标签: c++ c++11 compilation unordered-set


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果您无法提供std::hash&lt;E&gt;,您可以切换到std::map,但会更慢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-11
      • 2015-06-22
      • 1970-01-01
      • 2012-08-01
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      相关资源
      最近更新 更多