Jowi
Jowi

Reputation: 21

Dynamic array of Maps in C++

In a program which I'm coding I need to use an structure as this one:

static std::unordered_map<size_t, int> map[N][M];

The problem is that I need to generate the size of the map dynamically, so I would define:

static std::unordered_map<size_t, int> **map

But I'm having problems allocating it. Any suggestion?

Thanks

Upvotes: 0

Views: 1650

Answers (2)

Galik
Galik

Reputation: 48615

I recomment you use std::vector to manage your arrays. You can create a vector of vectors like this:

std::vector<std::vector<std::unordered_map<size_t, int>>> map(M, std::vector<std::unordered_map<size_t, int>>(N));

for(int m = 0; m < M; ++m)
{
    for(int n = 0; n < N; ++n)
    {
        map[m][n].emplace(0, 1);
    }
}

If you know the sizes at compile time, you can use std::array which should be faster.

static std::array<std::array<std::unordered_map<size_t, int>, M>, N> map;

Upvotes: 2

Jay
Jay

Reputation: 656

You only need to allocate the space of N * sizeof(std::unordered_map<size_t, int> *).

Upvotes: 0

Related Questions