Search code examples
c++vector2dtile

Converting a 1D vector into 2D


I have a problem, I am making a RPG game with C++, and here is my problem:

I have a 1D vector that contains "gid" elements of tiles in my game, like this picture:

https://i.sstatic.net/rrAc9.png

This 1D vector contains 400 elements (my map is 20x20), and I want to convert it to a 2D vector, so I can then create a grid of tiles...

I have tried this:

map_floor2D.resize(map_floor.size(), map_floor);
    for (int i = 0; i < map_floor2D.size(); i++)
    {
        for (int j = 0; j < map_floor2D[i].size(); i++)
        {
            cout << map_floor2D[i][j];
        }
    }

map_floor is the 1D vector. map_floor2D is the 2D vector

How can I do that?


Solution

  • vector<int> map_floor1D;
    vector<vector< int> > map_floor2D;
    map_floor2D.resize(20);
    for (int i = 0; i < 20; i++)
    {
        map_floor2D[i].resize(20);
    }
    for (int i = 0; i < map_floor1D.size(); i++)
    {
        int row = i / 20;
        int col = i %20;
        map_floor2D[row][col] = map_floor1D[i];
    }