lefk36
lefk36

Reputation: 9

Is there any way to give different names to the members of an array?

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

Answers (2)

schlebe
schlebe

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

Stf Kolev
Stf Kolev

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

Related Questions