5Mixer
5Mixer

Reputation: 531

C++ 2D vector maps

First of all, I know this question has been asked alot, but I need to clarify and understand some things. Also, I am still learning c++, currently from a book and tutorials, so don't be harsh :)

How can I have a 2D map for a platformer defined in code and modified? I understand basic multidimentional arrays, but I really can't use them because the size of my map will be changing alot. I can use a vector of vectors, but from what I have heard, this isn't a rectangular grid any more, it is more like...

x x x x x x x x x x   
x       x . . . . .
x       x . . . . .
x x x x x x x x x x

Where x is a tile, space is an air tile, and a dot is not allocated. Not a grid!

I am also confused on how pointers of arrays work.

Sorry for being abit of a noob here, I am still trying to work things out.

Any help would be greatly apprieciated!

Upvotes: 1

Views: 1010

Answers (1)

Marco A.
Marco A.

Reputation: 43662

I would definitely go for a vector of vectors if you need a simple resizable matrix class. You can always wrap this into a Matrix class on your own (perhaps by templating the dimensions/types)

struct Tile {
    int whatever = 0;
};

int main() {
    std::vector<std::vector<Tile>> m;
    m.resize(10);
    for(auto& v : m)
        v.resize(10);

    // Print a 10x10 0-initialized matrix
    for(auto& v : m) {
        for(auto& elements : v)
            std::cout << elements.whatever << " ";
        std::cout << std::endl;
    }
}

Live example

Memory in a vector is contiguously allocated, there are no "holes". Anyway you'll have to keep the dimensions of the inner vectors in sync if you resize one.

If you believe this is too much work for what you have in mind, go for Boost BLAS capabilities with Matrix.

Upvotes: 1

Related Questions