编译错误:void 值没有被忽略,因为它应该在 std::queue::pop()

2022-01-21 00:00:00 queue c++ std

编写一个函数,将二叉树中同一级别的所有相邻节点连接起来.给定二叉树节点的结构如下.

Write a function to connect all the adjacent nodes at the same level in a binary tree. Structure of the given Binary Tree node is like following.

struct Node{
  int data;
  Node* left;
  Node* right;
  Node* nextRight; 
}

最初,所有 nextRight 指针都指向垃圾值.您的函数应将这些指针设置为指向每个节点的右下角.

Initially, all the nextRight pointers point to garbage values. Your function should set these pointers to point next right for each node.

我的代码是

#include<queue>
/*
Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function would be added by GfG's Online Judge.*/


/* struct Node
{
  int data;
  Node *left,  *right;
  Node *nextRight;  // This has garbage value in input trees
}; */
// Should set the nextRight for all nodes
void connect(Node *p)
{
   Node *temp=p;
   queue<Node *> q;
   Node *pp=NULL;
   q.push(p);
   q.push(pp);
   while(q.empty()==false)
   {
       Node* nn=q.pop(); //  <---------- Error appears here
       Node* conn=NULL;
       if(nn!=NULL)
       {
           conn=q.front();
           nn->nextRight=conn;
           if(nn->left!=NULL)
               q.push(nn->left);
           if(nn->right!=NULL)
               q.push(nn->right);
       }
       else if(q.empty()==false)
       {
           q.push(pp);
       }

   }

}

它给出了这个错误:

Compilation Error... 
prog.cpp: In function 'void connect(Node*)':
prog.cpp:120:23: error: void value not ignored as it ought to be
        Node* nn=q.pop();
                       ^

帮助我运行代码而不出现此错误.

Help me to run the code without this error.

推荐答案

std::queuepop 函数不会返回弹出的元素,它只会移除前面的元素,所以你必须先调用 q.front() 然后调用 q.pop().

std::queue's pop function doesn't return the popped element, it only removes the front element, so instead you first have to call q.front() and then call q.pop().

Node* nn=q.pop();

变成:

Node* nn=q.front();
q.pop();

如果你愿意,你可以写一个这样的辅助函数:

If you want you can write a helper function like this:

template<class T>
auto popget(T& queue)
{
    auto ret = std::move(queue.front());
    queue.pop();

    return ret;
}

然后你可以简单地这样写你的代码:

Then you can simply write your code this way:

Node* nn=popget(q);

相关文章