0
list<int>* compare(){
    list q;
    q.push_front(1);
    q.push_front(2);
  
return &q;

}

this method returns a pointer to an empty list
how can I do to return priority_queue contain 1,2.

Edited by eman 22: n/a

2
Contributors
4
Replies
7
Views
5 Years
Discussion Span
Last Post by Moschops
Featured Replies
  • If you send the list by value (i.e not as a reference) then the function gets a [I]copy[/I] of the list, so when you return a reference to that copy, you have the same problem (as the copy is destroyed). If you have the problem when you send a reference … Read More

0

This function creates a list, named q, on the stack. That object q is destroyed when you return from this function. If you want to return a pointer to an object, you will have to do something to ensure that the object exists after the function returns.

This is commonly done by creating the object before you call the function, and passing the object to the function using a pointer or as a reference, or you can create the object dynamically within the function using new such that it won't be destroyed until you delete it.

Edited by Moschops: OP changed the code, so I had to change my answer.

0

I tried to create the list in main and then send it as a parameter to method compare and return a reference do it.

and also tried to send a reference to this list.

but I'm still have the same problem.

1

If you send the list by value (i.e not as a reference) then the function gets a copy of the list, so when you return a reference to that copy, you have the same problem (as the copy is destroyed).

If you have the problem when you send a reference to the list, then I expect the mistake is somewhere else.

The following code works by passing the function a reference to the list.

#include <list>
#include <iostream>

using std::cout;
using std::list;


void changeList(list<int>& q)
{
    q.push_front(1);
    q.push_front(2);
    return;};
 
int main()
{

  list<int> aList;
  changeList(aList);
  cout<<aList.front() << std::endl;
  cout<<aList.back();

  return 0;
 
}

Edited by Moschops: n/a

Comments
Thanks you this helped me a lot!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.