I'm making a chess program and want to make a function that checks the directions a piece can move.
For example, if the piece is a queen, the function will check how far in each direction the queen can move before hitting the edge of the board or running into another piece. I want to return something that will have a numerical val开发者_开发问答ue for each direction, North, Northeast, South, etc Something like this
return [1,2,3,4,5,6,1,2]
Can I return various numbers like that to an array?
You can't return an array from a function -- but you can return a vector, which is what you should probably be using instead of an array in any case.
You can return a structure, you can return a pointer to an array (if you declare it on the heap using malloc)...
You can return more than one value in a C++ function by passing aditional arguments by reference, which you can use for the return values.
Another alternative, less efficient but perhaps more "beautiful" and often used in Java is creating a data structure to hold the arguments you need to return, and returning an object with such values.
What about using a map where the key is direction and the value is the number allowed in each direction? You could create a simple enum to represent the various directions:
std::map<Direction, unsigned int>
So, in your example, the data in the map would look like this:
NORTH -> 1
NORTHEAST -> 2
EAST -> 3
etc.
Return a vector of tuples, with each tuple containing two integers: the number of squares the piece can move in the x and y directions, respectively.
Doing it that way will allow you to represent knights' movements, castling, etc.
Yes, but the better solution would be to return a class AllowedMoves
. The data members of this class would be private, and the test functions (e.g. bool canMoveTo(int row, int col) const;
) would be public. If you later discover that you'd want another internal data format, you can fix that inside the class, without changes everywhere.
精彩评论