I'm creating text based TicTacToe in C++ and need to create a function that checks for a win.
Right now, I have a vector of all the moves player X has made:
std::vector<int> x_vector = {1, 2, 3, 5, 7};
I also have a 2d vector of win conditions:
std::vector<std::vector> > wins = {{1, 2, 3}, {4, 5, 6}, {7, 8, 8}};
In this case, each element of the wins vector represents a win condition. If player X ever has a combination of inputs in their vector that includes one of the win conditions, I'm trying to get a bool function to return true.
I'm new to C++ and coding in general, so all patience is appreciated, and the simpler the solution you can help me find the better.
You can iterate through your list of known wins, checking each to see if it is a subset of the list of user's moves. The
std::includesfunction will do this test – but note that the two 'lists' need to be sorted.To avoid having to manually sort the list of user's moves after each input, you can use the
std::setcontainer (which is inherently sorted), instead ofstd::vector.The following snippet shows a relatively simple implementation of an
isWin()function using this approach, along with some rudimentary test cases:Note that this approach may not be the best for checking wins in a Tic-Tac-Toe game; however, if your purpose is to learn about vectors, sets and looking for matching sub-sequences, it may provide a useful starting-point.
For your actual user input, you would declare and initialize an empty set and then add moves using the
insertmember function of thestd::setcontainer class; something like this: