Initializing a large const array?

Anyway, to initialize a large const array without putting all the elements inside it, like this:

trying to create an array:

const double A[1000] = {1.0/1, 1.0/2, 1.0/3,...,1.0/1000};

      

It's easy to do with a loop.

+3


source to share


4 answers


If it really should be const, and you have 1000 different values, write some kiddy / script application to spit it out as a header file and prevent text from being entered! This gives you an easy way to change the initialization of the entire array later if needed.



+4


source


To do this, you can use the boost preprocessor library:

Your main file:

#include <boost/preprocessor.hpp>


const double A[1000] = {
#define BOOST_PP_ITERATION_LIMITS (0, 9)
#define BOOST_PP_FILENAME_1 "toplevel.hpp"
#include BOOST_PP_ITERATE()
};

      

File "toplevel.hpp"

:

#define ENUMERATE(z, i, data) 1.0 / (BOOST_PP_ITERATION() * 100 + i)

BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(100, ENUMERATE, %%)

#undef ENUMERATE

      

It works by including "toplevel.hpp" ten times in a row, while BOOST_PP_ITERATION()

expanding to 0, 1, .. 9 on each iteration (0 and 9 comes from BOOST_PP_ITERATION_LIMITS

).

BOOST_PP_COMMA_IF()

creates a comma if the argument is nonzero.



BOOST_PP_ENUM()

expands the macro ( ENUMERATE

in this case) 100 times and i

gets values ​​from 0 to 99 (based on the argument 100

).

EDIT

Added explanation and removed unnecessary BOOST_PP_OR()

.

EDIT 2

This two-step iteration (file and macro inside it) should be used as most of the iteration schemes in boost :: preprocessor are limited to max. 256 iterations (as stored in various macros BOOST_PP_LIMIT_*

).

It can also be done using nested BOOST_PP_ENUM () without iterating over the file.

+3


source


If I had to do this, I would probably write a small program to do this:

for(i = 1; i <= 1000; i++)
{ 
    printf("1/%d.0, ", i);
    if(i % 10 == 0) printf("\n");
}

      

I thought you could do it with macros and I'm sure it can be done, but I can't get it to work right now. I will return if I earn.

+1


source


You can create an array of pointers to const char so that you can initialize them at runtime with new with a loop.

Otherwise, I don't believe there is a way. You can either just go ahead, initialize it manually in the header file, or strip it out of status const

. If it doesn't initialize at compile time, the compiler complains that it doesn't initialize the variable const

.

0


source







All Articles