Float L/c - 1;
Int nodes [c - 1] [2];
Int belongs [c];
C value must be through the size of DBB to know exactly how much, but behind the defining constants L [], nodes [] [], belongs [] when I was an error, says c value must be a constant value, and how to solve the problem of
CodePudding user response:
C value only at run time by calling the DBB. Know the size, so the compiler can't know the size of the c at compile time, also cannot give L, nodes, belong allocate space, should be to define c as constant, or to use dynamic memory allocation,CodePudding user response:
Dynamic array, using a pointer, dynamically allocated memoryCodePudding user response:
Because of the built-in c + + array subscript can only support a constant or constexpr expression, so he created an array or a 2 d array class template, like the following, can realize dynamic dimension:
using namespace std;
Template
Class Array2D//said two-dimensional array class
{
Public:
Class Array1D//said one dimensional array class
{
Public:
Array1D ()=default;
T& Operator [] (size_t index)
{
Return const_cast & lt; T&> (static_cast & lt; Const Array1D & amp;> (* this) [index]);
}
Const T& Operator [] (size_t index) const
{
Return arr1 [index];
}
Auto& CreateArr1D (size_t nums)
{
Arr1. Reset (new T/nums);
Return arr1;
}
Array1D (const Array1D & amp;)=the delete;
Array1D & amp; Operator=(const Array1D & amp;)=the delete;
//...
Private:
Unique_ptr & lt; T [] & gt; Arr1 {nullptr};
};
Array2D (size_t dim1, size_t dim2, initializer_list & lt; T> Il={})
{
Arr2. Reset (new Array1D [dim1]);
For (size_t I=0; I & lt; Dim1; I++)
Arr2 [I] CreateArr1D (dim2);
//, initializer array value
Size_t num=il. The size ();
If (num & gt; 0)
{
int i=0;
For (auto p=il. The begin (); P!=il. End (); + + p)
{
i++;
Arr2 [((I - 1)/dim2) % dim1] [dim2 (I - 1) %]=* p;
}
}
}
Array1D & amp; Operator [] (size_t index)
{
Return const_cast & lt; Array1D & amp;> (static_cast & lt; Const Array2D & amp;> (* this) [index]);
}
Const Array1D & amp; Operator [] (size_t index) const
{
Return arr2 [index];
}
Array2D (const Array2D & amp;)=the delete;
Array2D & amp; Operator=(const Array2D & amp;)=the delete;
//...
Private:
Unique_ptr & lt; Array1D [] & gt; Arr2 {nullptr};
};
//Test:
Int main ()
{
Int x=3;
Int y=5;
Array2D & lt; Int> P (x, y);
P [0] [0]=100;
P [2] [4]=200;
Cout & lt;
Array2D & lt; Int> P2 (x, y,,2,3,4,5,6,7,8,9,10,11,12,13,14,15 {1});//to the initial value
Cout & lt;
X=y=2;
Array2D & lt; String> S (x, y, {" ABC ", "def"});
Cout & lt;}