Reserve 2D Vector in C++ and copy data from array

I hope to use vector to process the 2d array data obtained by calling a third-party library.

Although I can simply use the loop to assign values one by one, But I prefer to use methods such as insert and copy to deal with this.

I found that reserve doesn’t seem to work here. So I used resize instead.

double **a = new double *[1024];
for (int i = 0; i < 1024; ++i) {
    a[i] = new double[512];
}

std::vector<std::vector<double>> a_v;
a_v.resize(1024, std::vector<double>(512));

// Copy a -> a_v

I made these attempts:

// Not Working, just 0 in vector
for (int i = 0; i < 1024; ++i){
    a_v[i].insert(a_v[i].end(), a[i], a[i] + 512);
}

Is there any good way to solve this problem.

For a 1D array I write like this:

double *b = new double[1024];
std::vector<double> b_v;

b_v.reserve(1024);
b_v.insert(b_v.end(), b, b + 1024);

>Solution :

If the size of the source array is fixed, it is strongly recommended to use std::array instead of std::vector. std::array has continuous memory layout for multidimensional structures, thus std::memcpy can be used for copy if the source array is also continuous in memory.

Look back to the original question. If you want to construct a std::vector<std::vector<double>> from the source array, use a single loop to construct 1D vectors from the source:

for (int i = 0; i < 1024; ++i) {
    a_v.emplace_back(std::vector<double>(&(a[i][0]), &(a[i][512])));
}

If there is already a std::vector<std::vector<double>> with the proper size, and you literally want to do a copy from the source, use the assign member function:

for (int i = 0; i < 1024; ++i) {
    a_v[i].assign(&(a[i][0]), &(a[i][512]));
}

Leave a Reply