![](/img/trans.png)
[英]How to convert a string containing multiple numbers to ints and store it in a vector
[英]How to turn a string containing tile numbers into a map or vector that contains coordinates of the tilenumber?
I am using tinyxml2 ( https://leethomason.github.io/tinyxml2/index.html ) to parse a.tmx/.xml file to C++. 有一個名為 data 的 ChildElement,它有文本內容。
<data encoding="csv">
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,
3,3,0,2,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,3,
3,3,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,3,
3,3,4,0,0,3,3,3,3,3,3,3,3,3,3,3,4,0,3,3,
3,3,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,
3,3,3,3,4,0,0,0,2,2,2,2,2,2,2,0,0,0,5,3,
3,3,3,3,3,4,0,6,6,6,0,0,0,0,0,0,0,5,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3
</data>
我通過 tinyxml function GetText() 獲取文本。 所以每個 ',' 等於一列 -> x 坐標,每個 '\n' 限制行 -> y 坐標。 我試圖將坐標和 tilenumbers 放入 std::map,它只包含 integer 值(x,y,tilenumber)。 到目前為止,我的工作解決方案看起來像下面的代碼。 現在我正在尋找更好的解決方案。 目前我只保存這條線,我會從向量中的 position 獲得 x。
XMLElement* pData = pLayer->FirstChildElement("data");
if (pData != NULL)
{
std::stringstream gidList;
gidList.str(pData->GetText());
std::vector<std::string> LineList;
std::map<int, std::vector<int>> gidDataList;
std::string gidLine;
while (std::getline(gidList, gidLine, '\n'))
{
LineList.push_back(gidLine);
}
for (int line = 0; line < LineList.size(); line++)
{
std::string tilenumber;
std::stringstream LineListStream(LineList.at(line));
while (std::getline(LineListStream, tilenumber, ','))
{
gidDataList[line].push_back(std::stoi(tilenumber));
}
}
}
我認為您混淆了std::map
的目的,更有效的實現可能會改用std::vector
之類的東西。 在使用非整數鍵映射對時,映射可能會很有幫助,但對於像這樣的應用程序,它們是多余的。
#include <string>
#include <vector>
std::vector<std::vector<unsigned int>> parse_tiles(const std::string &gid_list) {
std::vector<std::vector<unsigned int>> tiles;
std::string value;
unsigned int row = 0;
for(unsigned int index = 0; index < gid_list.length(); index += 1) {
if(gid_list[index] == ',') {
tiles[row].push_back(std::stoi(value));
value.clear();
}
else if(gid_list[index] == '\n') {
tiles[row].push_back(std::stoi(value));
value.clear();
tiles.push_back();
row += 1;
}
else if(gid_list[index] >= '0' && gid_list[index] <= '9')
value += gid_list[index];
}
return tiles;
}
通過這個示例,您應該能夠以與之前幾乎相同的方式訪問元素。 例如,斷章取義:
const auto tiles = parse_tiles(pData->GetText());
std::cout << "tile at (x = 2, y = 4) = " << tiles[4][2] << "\n";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.