I am doing a very simple exercise on C++ recursion for reversing a stack recursively. The code is attached below. My problem is about whether I should use reference T& or simply T in my recursive call putToBottom(stack&, const T&).
#include <iostream>
#include <stack>
using namespace std;
template <typename T>
void putToBottom(stack<T>& myStack, const T& topOne)
{
if (myStack.empty())
{
myStack.push(topOne);
return;
}
//Should I use T& or T here???
***T temp = myStack.top();***
myStack.pop();
putToBottom(myStack, topOne);
myStack.push(temp);
}
template <typename T>
void reverseStack(stack<T>& myStack)
{
if (myStack.empty()) return;
T& topOne = myStack.top();
myStack.pop();
reverseStack(myStack);
putToBottom(myStack, topOne);
}
int main()
{
stack<int> myStack;
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
reverseStack(myStack);
while (!myStack.empty())
{
cout << myStack.top() << "\n";
myStack.pop();
}
cout << endl;
return 0;
}
If I write T temp = myStack.top();
, I get the right answer (the stack is now 1 (top) -> 2 -> 3 -> 4). However, if I write T& temp = myStack.top();
or const T& temp = myStack.top();
, I get the wrong one (the stack becomes 4 (top) -> 4 -> 4 -> 4). Any ideas would help! Thank you!
If you use T& temp = myStack.top()
, then once you do myStack.pop()
, temp
becomes a dangling reference and it is undefined behavior to use it further.
If you are using C++11 then you probably want move semantics:
T temp = std::move(myStack.top());
myStack.pop();
putToBottom(myStack, topOne);
myStack.push(std::move(temp));
And similarly in reverseStack
.
Although I have to note, this is a particularly inefficient way to reverse a stack. Better would be simply to pop everything off of the original stack while pushing it onto a second stack.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.