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 << "\nUndoing 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.
undoMovealways returns aarray<string, 100>. That array will never be empty. Yourarr = array<string, 100>();in theelsepart of the function gives you a non-empty array of 100 default-constructed (empty) strings. - Kevinarray<string, 100>();I will be initializing an empty array and forgot it will already be full, silly me. thank you for pointing this out - kaMOONstd::stackright? I can still check if it's empty that way right? or because it's a stack of arrays this is not allowed? - kaMOON