Reputation: 111
I'm trying to declare a 2d array by using the size() method for STL map:
const int size = edge_map.size();//get row and column size
int a[size][size];//nxn matrix
I keep getting a compiler error that the size must be a constant value even though I am declaring it as a constant. Is there any work around for this without having to use a dynamic 2d array?
Upvotes: 3
Views: 74
Reputation: 14131
const
means to not change its original (initial) value.
But size
must be known at compile time, as the compiler/linker allocates memory for non-local variables (declared out of any function).
Upvotes: 1
Reputation: 6755
Static memory allocation for arrays can accept variables as long as the value of the variable can be determined at compile-time. The reason for this requirement is because the compiler must know how much memory to allocate for the array on the stack. If edge_map
is what it sounds like (some kind of container which can change sizes throughout its existence), you are not going to be able to do it this way.
If this is not the case, though, and edge_map.size()
has a return value which can be determined at compile-time, marking that function as constexpr
should allow this code to work.
Upvotes: 3