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 5 Years Ago by eman 22: n/a

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 5 Years Ago by Moschops: OP changed the code, so I had to change my answer.

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.

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 5 Years Ago by Moschops: n/a

Comments
Thanks you this helped me a lot!
This question has already been answered. Start a new discussion instead.