I have been learning C++ for a couple of weeks now and started making my game where I pumped into this problem with std::stack.
I have a class that have a board and a stack
#include <string>
#include <stack>
array<string, 100> board;
stack<array<string, 100>> history;
each time I create my board or make changes I push it to the stack simply by history.push(board)
.
I have made an undo function that looks like this:
array<string, 100> Board::undoMove(stack<array<string, 100>> &history){
array<string, 100> arr;
if(!history.empty()){
history.pop();
arr = history.top();
}
else{
arr = array<string, 100>();
}
return arr;
}
when calling it:
array<string,100> tempState = b.undoMove(history);
if(!tempState.empty()){
board = tempState;
cout << "
Undoing your latest move.. "<< endl;
}
else{
cout << "No previous move available" << endl;
}
Apparently, this function works only if I make an undo move after the first change to the board. After a couple of changes, my program stops after a pause.
I'm not really good with debugging so I couldn't figure out what is wrong and where. I'm making this game so It helps me understand how stacks work but I don't think this is going anywhere! I think there is something wrong with how I think the stack should work in this case.
Also, some people suggested that the fact the stack is a stack of std::array
creates the problem when I'm pushing to it but that doesn't sound right, so I'm very confused about how I should look at this problem or think of it and I'm looking for any suggestions I could get.
question from:
https://stackoverflow.com/questions/65877310/implementation-of-stack-arraystring-100 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…