简体   繁体   中英

Find coordinates of a char in a vector of strings (C++)

I am programming a simple ASCII Roguelike RPG in C++, and I am using the @ character to represent the player, as usual.

I store the levels in .txt files, so that people with no programming knowledge can edit and create their own levels.

When I run the game, I open the first level file and push_back the level line by line into a vector of strings.

I can access a certain char in the vector via its coordinates, eg:

char certainChar = levelData[3][3];

I am asking for the fastest way to do the reverse: getting the coordinates of a char which only appears once in the vector.

Any suggestions?

This boils down to searching in an unordered list/array.

For each line: for each char in this line: is this the desired char? -> yes -> record indexes and return.

If your levels are small this is OK.

A quicker way would be to store the @-coordinates separately in your level file and of course keep track of them during program execution.

Try using this function

std::pair<int, int> findCoordinates(std::vector<std::string> > & levelData) {
    for (unsigned int i = 0; i < levelData.size(); ++i) {
        std::size_t found = levelData[i].find('@');
        if (found != std::string::npos) return std::make_pair(i, found);
    }
    return std::pair<int, int>();
}

But this may be very slow for large vectors containing long strings.

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