samedi 31 mars 2018

Initialize std::array with a random size

I have two macros:

#define length(array) sizeof(array)/sizeof(array[0])
#define randRange(x,y) x + ( std::rand() % ( y - x + 1 ) )

I Can do this:

int data[] = {2, 3, 34, 10, 3, 12, 30 };
const int arr_length = length(data);
std::array<int,arr_length> data_std_array;

I Can initialize with a constant:

const int arr_length = 500;
std::array<int,arr_length> data_std_array;

But I can't initialize an std::array with my rand function:

float a = randRange(2, 200);
const int arr_length = (int)a;
std::array<int,arr_length> data_std_array;

float a = randRange(2, 200);
int counter = 0;
for(int i =0; i < a; i++){
    counter++;
}
const int arr_length = counter;
std::array<int,arr_length> data_std_array;

float a = randRange(2, 200);
const int arr_length = static_cast<int>(a);

None of these work.

I've tried all sorts of variables like size_t and unsigned ints, constants, pointers etc. I always get this error message

Error msg I always receive: float a = randRange(2, 200); const int arr_length = static_cast(a);

/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp: In member function ‘virtual void algorithmTest_TestAlgorithmRandomArray_Test::TestBody()’:
/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp:87:20: error: the value of ‘arr_length’ is not usable in a constant expression
     std::array<int,arr_length> data_std_array;
                    ^
/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp:76:15: note: ‘arr_length’ was not initialized with a constant expression
     const int arr_length = static_cast<int>(a);
               ^
/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp:87:30: error: the value of ‘arr_length’ is not usable in a constant expression
     std::array<int,arr_length> data_std_array;
                              ^
/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp:76:15: note: ‘arr_length’ was not initialized with a constant expression
     const int arr_length = static_cast<int>(a);
               ^
/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp:87:30: note: in template argument for type ‘long unsigned int’ 
     std::array<int,arr_length> data_std_array;

How can I initialize and std array with a random length in range?

Aucun commentaire:

Enregistrer un commentaire