Currently I have a vector holding references to all the rooms connected to a specific room:
rooms.at(1).connectedRooms = { &rooms.at(2), &rooms.at(3), &rooms.at(4), &rooms.at(5)};
However I would like to use my enum as the index, rather than an integer, so instead of rooms.at(1).connectedRooms.at(0) I would use rooms.at(1).connectedRooms.at(NORTH) which makes much more sense and also allows it to be used more easily and legibly in switch statements.
The enum looks like
enum directions { NORTH, EAST, SOUTH, WEST};
Is there a way to do this on one line, for example (this code doesn't work, but it's what I would like to do):
rooms.at(1).connectedRooms[NORTH, EAST, SOUTH, WEST] = {&rooms.at(2), &rooms.at(3), &rooms.at(4), &rooms.at(5)};
Rather than the much longer
rooms.at(1).connectedRooms[NORTH] = &rooms.at(2);
rooms.at(1).connectedRooms[EAST] = &rooms.at(3);
rooms.at(1).connectedRooms[SOUTH] = &rooms.at(4);
rooms.at(1).connectedRooms[WEST] = &rooms.at(5);
Thanks
2 个答案:
答案 0 :(得分:1)
You can assign integer values to your enum constants:
enum directions { NORTH = 0, EAST = 1, SOUTH = 2, WEST = 3 };
and then you keep the assignment as is:
rooms.at(1).connectedRooms = { &rooms.at(2), &rooms.at(3), &rooms.at(4), &rooms.at(5)};
EDIT: as per the comment below, please be aware that the way you are holding pointers to vector members is VERY dangerous and is not considered good practice. Remember that an std::vector is dynamic, so it may decide to change the location of its memory area anytime it needs to, such as when it grows...
答案 1 :(得分:0)
Assuming that you will keep your enums and room values defined in that order, you can try this approach:
auto& vec = rooms.at(1).connectedRooms;
for (int i = 0; i < 4; i++)
{
vec[i] = &rooms.at(i + 2);
}