Reputation: 9
For example I am making a Pacman
game and I am using a struct
array to represent the ghosts.
But is there any way to change the ghost[0]
expression to Inky
?
Upvotes: 0
Views: 129
Reputation: 3716
You can define a reference to any item in your struct
array.
Example:
Ghost &inky = ghosts[0];
Ghost &blinky = ghosts[1];
Ghost &pinky = ghosts[2];
Ghost &clyde = ghosts[3];
To respect C++ convention, I recommand that all these references are defined with a name that begin with a lower case.
You can then use all these references as normal variables using .
to call member's functions or to read or assign member's variables.
Example:
inky.setBackColor(blue);
inky.remove();
clyde.size += 2;
Upvotes: 2
Reputation: 730
It seems you are looking for associative array. Associative array is an array that can be accessed with something like association. For example, if you want to access your fruits array and get the apple, you could do: fruits["apple"]
and get the value, instead of wondering which index the apple was.
If this is what you are really looking for, then in C++ it is called a map. The map is the same as associative array. Take a look onto how to use it.
https://en.cppreference.com/w/cpp/container/map
Upvotes: 2