编译错误:void 值没有被忽略,因为它应该在 std::queue::pop() [英] Compilation Error: void value not ignored as it ought to be in std::queue::pop()

查看:36
本文介绍了编译错误:void 值没有被忽略,因为它应该在 std::queue::pop()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于编译错误:void 值没有被忽略,因为它应该在 std::queue::pop()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆