I am mostly a C programmer, and I am looking for a fast and elegant solution to do what I want in C++. Let us consider this simple data structure
struct mystruct
{
int * array1;
int * array2;
size_t size;
};
The two pointers array1
and array2
are to be thought as two arrays of length size
. I need a huge amount of these (about 2**30
or 1.000.000.000
) all of the same small size (about 100
). All of them will be deallocated at the exact same time. I can do the following in C with only one call to malloc
where K
is the number of struct I need and N
is the size of the arrays
EDITED VERSION (see the old one below)
size_t NN = N * sizeof(int);
struct mystruct * my_objects = malloc(K * sizeof(struct mystruct));
int * memory = malloc(2*K*NN);
for(i=0; i<K; ++i)
{
my_objects[i].size = N;
my_objects[i].array1 = memory + 2*i*NN;
my_objects[i].array2 = memory + (2*i+1)*NN;
}
...
free(my_objects);
free(memory);
This version does not support very huge K
and does not allow me to resize the array. But it is not so hard to design something for that purpose. Is there a way of creating a class in C++ that would be a kind of std::vector<mystruct>
with forbidden shrinking and for which the allocation of array1
and array2
would not be based on dynamical allocation for each entry? I do want to minimize the effect of memory allocation since K
is very big.
OLD VERSION:
size_t KK = K * sizeof(mystruct);
size_t NN = N * sizeof(int);
struct mystruct * my_objects = (struct mystruct *) malloc(KK + 2*K*NN);
for(i=0; i<K; ++i)
{
my_objects[i].size = N;
my_objects[i].array1 = (int *) (my_objects + KK + 2*i*NN);
my_objects[i].array2 = (int *) (my_objects + KK + (2*i+1)*NN);
}