繁体   English   中英

递归无序映射

[英]Recursive unordered_map

我有一个内部使用无序 map 的树结构

#include <unordered_map>

struct Node {
        std::unordered_map<int, Node> children;
};

int main() {
        Node a;
}

它在 Apple clang 11.0.3 和 MSVC v19.24 上运行良好,但无法在 clang 10.0.0 和 ZE0D511356BD44120AF49CC011111 上编译。

虽然常规的std::map在所有编译器上都可以正常工作。 我没有找到造成这种差异的原因。 有没有办法使用std::unordered_map作为自身的值? 或者指针是这里唯一的解决方案?

这是编译器资源管理器链接https://godbolt.org/z/6eYch9

这是来自 gcc 的错误:

 #3 with x86-64 gcc 10.1 In file included from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/unordered_map:43, from <source>:1: /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/stl_pair.h: In instantiation of 'struct std::pair<const int, Node>': /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ext/aligned_buffer.h:91:28: required from 'struct __gnu_cxx::__aligned_buffer<std::pair<const int, Node> >' /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/hashtable_policy.h:233:43: required from 'struct std::__detail::_Hash_node_value_base<std::pair<const int, Node> >' /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/hashtable_policy.h:279:12: required from 'struct std::__detail::_Hash_node<std::pair<const int, Node>, false>' /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/hashtable_policy.h:1973:13: required from 'struct std::__detail::_Hashtable_alloc<std::allocator<std::__detail::_Hash_node<std::pair<const int, Node>, false> > >' /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/hashtable.h:173:11: required from 'class std::_Hashtable<int, std::pair<const int, Node>, std::allocator<std::pair<const int, Node> >, std::__detail::_Select1st, std::equal_to<int>, std::hash<int>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<false, false, true> >' /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/unordered_map.h:105:18: required from 'class std::unordered_map<int, Node>' <source>:4:39: required from here /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/stl_pair.h:218:11: error: 'std::pair<_T1, _T2>::second' has incomplete type 218 | _T2 second; ///< The second member | ^~~~~~ <source>:3:8: note: forward declaration of 'struct Node' 3 | struct Node { | ^~~~ Compiler returned: 1

STL 容器不需要使用不完整的类型。 如果您不介意额外的间接性,那么解决方法是std::map<int, std::unique_ptr<Node>>

这与做例如相同的问题

struct Node
{
    Node child;  // An instance of the full structure
};

在完全定义之前,您不能使用结构(或类),它位于结束处}

但是,您可以定义指向结构的指针,因为编译器不需要完整的结构定义,只知道结构的名称:

struct Node
{
    Node* child;  // Pointer to the structure
};

因此,要解决您的问题,您需要一个 map指针

std::unordered_map<int, Node*> children;

在编写 Trie 数据结构时遇到此问题,我注意到在最新的 clang(v14)和 GCC(v12)中,我没有收到错误,我的代码按预期运行,但低于这些版本(在 godbolt.com 上) ) 我犯了同样的错误。 这都是使用-std=c++14所以它不应该与标准相关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM