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.

Recommended Answers

All 4 Replies

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.

I got it.

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;
 
}
commented: Thanks you this helped me a lot! +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.