#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<float>> func(int M)
{
// res = matrix size MxM
vector<vector<float>> res;
float* buffer = static_cast<float*>(malloc(M * M * sizeof(float)));
res.reserve(M);
for (int i=0; i<M; i++) {
res.emplace_back(buffer + i * M, buffer + (i + 1) * M);
/// res[i] = compute_the_matrix();
}
return res;
}
I'm required to make a function that use vector<vector<float>>
to represent a matrix. However, it's inefficient because the rows might be at different location in memory, while a good matrix should have all its element in a continuous block.
To do this, I malloc
a continuous block of memory. Then initialize the vectors from this block.
Is this method safe and will the vectors free memory correctly when it's destructed? Another situation I can think of is if there's an exception in res[i] = compute_the_matrix();
, then we have a memory leak.
Edit: I think this code perform copy-constructor instead of move-constructor, so it's not what I'm looking for. So, how can I make a vector that is continuous in memory?