[英]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.我正在用 C++ 编写一个简单的 ASCII Roguelike RPG,我像往常一样使用 @ 字符来代表玩家。
I store the levels in .txt files, so that people with no programming knowledge can edit and create their own levels.我将关卡存储在 .txt 文件中,以便没有编程知识的人可以编辑和创建自己的关卡。
When I run the game, I open the first level file and push_back the level line by line into a vector of strings.当我运行游戏,我打开第一级文件和通过的push_back线水平线成字符串的向量。
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.一种更快的方法是将@-coordinates 单独存储在您的关卡文件中,当然在程序执行期间跟踪它们。
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.但是对于包含长字符串的大向量来说,这可能会非常慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.