Reputation: 47
I was trying to create a map to associate 2d arrays to characters. I tried to do it in this way:
map<char, bool[6][4]> m;
bool charA[6][4] = { 0,1,1,0,
1,0,0,1,
1,1,1,1,
1,0,0,1,
1,0,0,1,
1,0,0,1 };
m.insert(make_pair('a', charA));
But it doesn't work; maybe because the array is not dynamically allocated?
Upvotes: 2
Views: 717
Reputation: 32722
Since you are using c++ and have access to c++11 compiler or newer versions, use std::array
instead of the c-style array.
In your case, you can replace it with
std::array<std::array<bool, 4>, 6>
.
Now you can do as follows: See a demo
#include <array> // std::array
std::map<char, std::array<std::array<bool, 4>, 6>> m;
std::array<std::array<bool, 4>, 6> arr = { 0,1,1,0,
1,0,0,1,
1,1,1,1,
1,0,0,1,
1,0,0,1,
1,0,0,1 };
// now you can
m.emplace('a', arr); // construct the entry in-place (std::map::emplace)
Maybe because the array is not dynamically allocated?
This has nothing to do with the allocations, rather the problem is with the c-style arrays. You simply can not copy it to the map like that. In other words, not copyable!
More read:
Future reads:
As @TedLyngmo pointed out, in the given example, even the std::map::emplace
is used, a copy of the array (i.e. arr
) will take place. This could be much expensive for larger arrays or arrays with data types, which are expensive to copy. In that case, you need to use the std::map::emplace
, in the way shown in the linked website.
You can refer to the following examples for further examples:
Upvotes: 2