Initializing a large const array?
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.
source to share
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.
source to share
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
.
source to share