【问题标题】:Is it possible to create a 2D vector of structs?是否可以创建结构的二维向量?
【发布时间】:2015-03-31 02:30:24
【问题描述】:

到目前为止,我已经设置了一个 2D 整数向量(下面的代码可以运行),但我真正想要的是一个名为“small_tile”的结构的 2D 向量数组。

在这里,我想用 txt 文件中的数据填充结构的纹理 int。稍后我还将填充其他数据值 'tile_x, tile_y, r, c'。

希望我的问题很清楚

#include <iostream>
#include <fstream>
#include <vector>

struct smallTile
{
    int tile_x;
    int tile_y;
    int r;
    int c;
    int texture; // 0=grass, 1=sand, 2=... (get this data from txt file)
};

int main()
{
    int SMALL_TILE_VECTOR_ROWS = 5;
    int SMALL_TILE_VECTOR_COLUMNS = 6;

    //Create vector array: 5x6 containing nothing:
    std::vector<std::vector<int> > vvint(SMALL_TILE_VECTOR_ROWS, std::vector<int>(SMALL_TILE_VECTOR_COLUMNS));

    //Fill vector with file information. 
    std::ifstream file ("levelMap.txt");
    for(int r = 0; r < vvint.size(); r++)
    {
        for (int c = 0; c < vvint.at(0).size(); c++)
        {
            file >> vvint[r][c];
        }
    }
    file.close();

    //cout out the data inside the vector array so I can see it's working:
    for(int r = 0; r < vvint.size(); r++)
    {
        for(int c = 0; c < vvint.at(0).size(); c++)
        {
            std::cout<< vvint[r][c] << " ";
        }
        std::cout<< "\n";
    }

    return 0;
}

【问题讨论】:

    标签: c++ arrays vector struct


    【解决方案1】:
    std::vector <smallTile> smalltiles;
    

    // 有什么问题?

    【讨论】:

    • 我发誓我之前尝试过,但我遇到了一些超级疯狂的错误,我刚才又试了一次,它成功了。谢谢:)
    猜你喜欢
    • 2021-08-01
    • 2022-11-17
    • 2014-03-30
    • 2014-09-01
    • 1970-01-01
    • 2010-10-23
    • 2022-11-22
    • 1970-01-01
    • 2012-06-15
    相关资源
    最近更新 更多