I have experienced, that the stl pop function doesn't return anything.

How can I return the top element of my stack and delete it?

The top function is not a good solution, because it returns only a reference of the top element...

有帮助吗?

解决方案

If you don't need the element anymore after popping it just

// use element with
container.top();
// remove it
container.pop();

Otherwise make a copy of the object:

Element e = container.top();
container.pop(); // remove it
// feel free to use e, you made a copy of it

If you need to really delete it manually then you are not using any kind of smart pointer, which moves the problem to another topic.

其他提示

You should combine member functions top() and pop(). For example

#include <iostream>
#include <stack>

int main()
{
   std::stack<int> s( std::stack<int>::container_type { 1, 2, 3 } );

   while ( !s.empty() )
   {
      int x = s.top();
      s.pop();
      std::cout << x << ' ';
   }
   std::cout << std::endl;
}

The output is

3 2 1

In this example the element that is in the top of the stack is copied in variable x, that is v ariable x will contain a copy of the element.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top