简体   繁体   中英

C++ - How do I insert multiple values into a vector, each with a different index?

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

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...

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM