I am using a library that returns the image as a big 2D array int**
. I need to convert it into int*
1D array. I think I've managed to do it quite fast by copying memory blocks:
// have int labels** as 2D array, also have rows and cols
//create 1D array
int *labels1D = new int[rows*cols];
//copy contents
for(int i = 0; i < rows; i++) {
// Here I don't know anything about how those arrays were allocated
// Maybe std::copy would handle it for me?
std::copy_n(labels[i], cols, labels1D + i*cols);
}
So the first question is whether I can do something better here? Is everything safe here assuming that library is a black box?
I do not want much to modify the library code, but I've found additionally how the source array in my side library this->currentLabels
was created:
int** currentLabels; //in class declaration
...
// in the code
this->currentLabels = new int*[this->height];
for (int i = 0; i < this->height; ++i) {
this->currentLabels[i] = new int[this->width];
for (int j = 0; j < this->width; ++j) {
// some code for setting the value
}
}
Looks like the values for rows and cols are known.
So the second question is: can I modify this code to make it allocate the 2D array in one memory block:
this->currentLabels = malloc(nrows*sizeof(int*) + (nrows*(ncolumns*sizeof(int)));
to allow me then just map it somehow to my 1D array without copying memory?
int labels1D = labels; // would be an array of [rows*cols]
Aucun commentaire:
Enregistrer un commentaire