【问题标题】:c++:pair.h compiler error - pair has incomplete type [duplicate]c ++:pair.h编译器错误-对的类型不完整[重复]
【发布时间】:2017-03-07 00:50:52
【问题描述】:
#ifndef TRIEAPI
#define TRIEAPI

#include <vector>
#include <string>
#include <unordered_map>

using namespace std;

typedef struct NodeStruct
{
    bool validNgram = false;
    unordered_map<string, struct NodeStruct> children;
    struct NodeStruct* parent;
    string nodeWord;

    NodeStruct(struct NodeStruct* par, string w) : parent(par), nodeWord(w) {} //constructor (yeah, structs have them too)
    NodeStruct() {}
}Node;


void addNgramTrie(Node* root, string ngram);
void findNgramsTrie(Node* root, string query);
void splitText(string query, vector<string> &words);
void deleteNgramTrie(Node* root, string ngram);
void recursiveParentDeletion(Node* node, Node *root);


#endif // TRIEAPI

当我尝试编译程序时,我在此头文件中收到关于 pair.h 的错误(在 g++ 5.4 c++11 中编译):

trie.h:14:46:   required from here
/usr/include/c++/5/bits/stl_pair.h:102:11: error: ‘std::pair<_T1, _T2>::second’ has incomplete type
       _T2 second;                /// @c second is a copy of the second object
           ^
In file included from trie.cpp:10:0:
trie.h:11:16: note: forward declaration of ‘struct NodeStruct’
 typedef struct NodeStruct

我不明白我错在哪里。

【问题讨论】:

标签: c++ struct unordered-map std-pair


【解决方案1】:
typedef struct NodeStruct
{
    bool validNgram = false;
    unordered_map<string, struct NodeStruct> children;

这不可能。想象一下,例如,unordered_map 的大小取决于它包含的类型的大小。这当然是可能的。因此,要知道unordered_map&lt;string, struct NodeStruct&gt; 的大小,您首先需要知道struct NodeStruct 的大小。但是由于一个struct NodeStruct包含这样一个unordered_map,所以还需要知道map的大小才能知道struct的大小。

这怎么可能起作用?也许在地图中使用unique_ptr&lt;struct NodeStruct&gt;

【讨论】:

  • 但是为什么当我使用地图而不是无序地图时我没有收到这个错误?
  • @JimS 语言级别答案:你很幸运,它不需要与std::map 一起使用。
  • @JimS 当你打破规则时,规则就会被打破。遵守规则,系统也会。 (我的论点表明它不能在一般情况下起作用,并不是说它不可能在特定情况下起作用。我的论点表明你不应该期望它起作用。)
  • 容器使用动态分配为其内容分配空间,因此具有自身容器的结构没有逻辑问题。只是不需要标准的标准库容器来支持它。你当然可以得到其他支持它的容器实现。
猜你喜欢
  • 2017-03-05
  • 1970-01-01
  • 1970-01-01
  • 2014-01-31
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
  • 2019-08-27
相关资源
最近更新 更多