使用队列(C++的STL)实现树时发生编译器错误



任何人都请告诉我为什么我的编译器会出现以下错误:

C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/ext/new_allocator.h: In instantiation of 'void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = Node*; _Args = {Node**}; _Tp = Node*]':
C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/alloc_traits.h:475:4:   required from 'static void std::allocator_traits<std::allocator<_CharT> >::construct(std::allocator_traits<std::allocator<_CharT> >::allocator_type&, _Up*, _Args&& ...) [with _Up = Node*; _Args = {Node**}; _Tp = Node*; std::allocator_traits<std::allocator<_CharT> >::allocator_type = std::allocator<Node*>]'
C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/deque.tcc:168:30:   required from 'void std::deque<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = {Node**}; _Tp = Node*; _Alloc = std::allocator<Node*>]'
C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_queue.h:268:4:   required from 'void std::queue<_Tp, _Sequence>::emplace(_Args&& ...) [with _Args = {Node**}; _Tp = Node*; _Sequence = std::deque<Node*, std::allocator<Node*> >]'
binaryTree.cpp:23:20:   required from here
C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/ext/new_allocator.h:136:4: error: cannot convert 'Node**' to 'Node*' in initialization
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

这是我的代码:

#include <iostream>
#include <queue>
using namespace std;
Node *root = NULL;
class Node
{
public:
int data;
Node *lchild;
Node *rchild;
};
void create()
{
Node *p, *t;
int x;
queue<Node *> q;
cout << "Enter root value: ";
cin >> x;
Node *root = new Node();
root->data = x;
root->lchild = root->rchild = 0;
q.emplace(&root);
while (!q.empty())
{
p = q.front();
q.pop();
cout << "Enter value for left child (-1 for NULL): ";
cin >> x;
if (x != -1)
{
t = new Node();
t->data = x;
t->lchild = t->rchild = 0;
p->lchild = t;
q.emplace(t);
}
cout << "Enter value for right child (-1 for NULL): ";
cin >> x;
if (x != -1)
{
t = new Node();
t->data = x;
t->lchild = t->rchild = 0;
p->rchild = t;
q.emplace(t);
}
}
}
void preorder(Node *p)
{
if (p)
{
cout << p->data << " ";
preorder(p->lchild);
preorder(p->rchild);
}
}
int main()
{
create();
preorder(root);
return 0;
}

问题是队列需要Node *值,而您正在传递Node **值。

q.emplace(root);替换q.emplace(&root);

最新更新