C ++ 2d array declaration with size function

I am trying to declare a 2d array using size () method for STL card:

const int size = edge_map.size();//get row and column size

int a[size][size];//nxn matrix

      

I keep getting compiler error that size should be constant even though I declare it to be constant. Is there any work around for this without using a dynamic 2d array?

+3


source to share


2 answers


const

means not to change the original (initial) value.



But size

must be known at compile time because the compiler / linker allocates memory for non-local variables (declared outside of any function).

+1


source


The 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 that the compiler needs to know how much memory is allocated for the array on the stack. If edge_map

- this is what it seems (some kind of container that can resize throughout its existence), you cannot do it.



If it doesn't, and edge_map.size()

has a return value that can be determined at compile time, labeling that function as it constexpr

should allow this code to work.

+3


source







All Articles