I have a function in which the nodes of a binary 'tree' are populated with values recursively computed based on the input vector, which represents the values on the leaves. An old C++ implementation of the function is as follows
using namespace std;
double f(const size_t h, vector<double>& input) {
double** x;
x = new double*[h+1];
x[0] = input.data();
for (size_t l = 1; l <= h; l++)
x[l] = new double[1<<(h-l)];
// do the computations on the tree where x[l][n] is the value
// on the node n at level l.
result = x[l][0];
for (size_t l = 1; l <= h; l++)
delete[] x[l];
delete[] x;
return result;
}
Now I'm trying to write a 'modern' implementation of the code using smart pointers in C++11/C++14. I attempted to define x
using std::unique_ptr
specialization for arrays so that I do not have to change the 'computation' procedure. The obvious problem with such an approach is that the contents of `input' will be deleted at the end of the function (because the unique pointer that takes the ownership of the data will be destroyed at the end of the function).
One simple (and perhaps safe) solution would be to allocate the memory for the whole tree (including the leaves) in x
and copy the values of the leaves from input
to x[0]
in the beginning of the function (in this case I can even used nested std::vector
s instead of std::unique_ptr
s specialized for arrays as the type of x
). But I prefer to avoid the cost of copying.
Alternatively one can change the computational procedures to read the values of the leaves directly from input
not from x
which requires changing too many small pieces of the code.
Is there any other way to do this?