Compilation Error: void value not ignored as it ought to be in std::queue::pop() [duplicate]

爷,独闯天下 提交于 2021-02-05 12:29:31

问题


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

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

My code is

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

   }

}

It gives this error:

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.


回答1:


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

becomes:

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



回答2:


Your error is quite simple; STL based containers that have pop and push algorithms do not return the value during the pop. Thus, you have to call std::queue::front() (Or back(), depending on what you need) on the container to get the value before popping it. For more details, read the answer to this question.



来源:https://stackoverflow.com/questions/48487678/compilation-error-void-value-not-ignored-as-it-ought-to-be-in-stdqueuepop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!