0

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

2

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Just a minor addition to this answer - in case if you know the size of your arrays at compile time - I'd suggest to use std::array instead of vector. This way the compiler can make better optimizations to your code
In this case I know the size on runtime. Using the vector approach I found a solution. static std::vector<std::vector<std::unordered_map<size_t, int>>> map; map.resize( num_of_col , std::vector<std::unordered_map<size_t, int>>( num_of_row ) );
@Chaosit Added a comment.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.