Fro
Fro

Reputation: 11

Is it possible to return something like this in C++?

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 value 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?

Upvotes: 1

Views: 123

Answers (6)

MSalters
MSalters

Reputation: 179789

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.

Upvotes: 0

Jeremy Friesner
Jeremy Friesner

Reputation: 73061

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.

Upvotes: 0

Clayton
Clayton

Reputation: 6271

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.

Upvotes: 0

Luis Miguel Serrano
Luis Miguel Serrano

Reputation: 5099

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.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490108

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.

Upvotes: 3

Brad
Brad

Reputation: 603

You can return a structure, you can return a pointer to an array (if you declare it on the heap using malloc)...

Upvotes: 0

Related Questions