0

I have this reverse method on my stack that reverses the elements inside the stack to a tmpStack. I want to know how to assign tmpStack to my original stack. I did not find a way to assign my original stack to that value so it can show up when I use print and not just print tmpStack. My problem is in the last lines.

template<class T>
void stack<T>::reverse(){

    T item;
    stack<T> tmpStack;

    while (empty() == false)
    {
        item = stack<T>::pop();
        tmpStack.push(item);
    }


    stack<T> = tmpStack;


}

1 Answers1

0

Assuming that your operator= is working correctly:

*this = tmpStack;

Edit:

As Toby hinted to correctly: Since C++11, the better way is

*this = std::move(tmpStack);

The difference: in your concrete case, none, as you do not provide a move assignment operator. But if you do so, the latter one would be called instead.

Stack& operator=(Stack&& other)
{
    // You do not copy the data any more here, but SWAP!
    // Swapping assures that, if *this has data allocated
    // other will clean it up correctly for you.
}

With such an assignment operator (and an appopriate move constructor, keyword rule of five), you get more efficient code as you save one step of data allocation and destruction (move instead of copy).

Community
  • 1
  • 1
Aconcagua
  • 24,880
  • 4
  • 34
  • 59