Question

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:

http://i.stack.imgur.com/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?

Was it helpful?

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];
}

OTHER TIPS

I wouldn't do any conversion at all. Just create a 2D view over the 1D data:

const int WIDTH = 16;

const int x = 5;  // 5 across
const int y = 6;  // 6 down

cout << map_floor[y*WIDTH + x];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top