In C++ I have a vector_map of the form <string, std::vector<double>>. I need to change those vectors of doubles to arrays of doubles so that I get an array_map of the form <string, double[]>
The problem is that when doing so, the arrays for every element in the map are the same and their elements are different from those of the original vectors. What I have right now is this:
map<string, double*> array_map;
for (auto it : vector_map){
double temp_arr[size of it.second as a const];
std::copy(it.second.begin(), it.second.end(), temp_arr);
array_map.insert({it.first, temp_arr});
}
>Solution :
You’re facing an issue here that’s to do with scope in C++. When you define that temp_arr in your loop, it’s a temporary variable, it only lives for the scope of that single loop iteration. When you pop it into your map, you’re storing a pointer to something that isn’t going to exist after the loop iteration ends. That’s why you’re seeing weird stuff in your array_map.
What you need to do is to dynamically allocate memory for those arrays. This way, they’ll stick around after your loop ends. You’d use the new keyword in C++. Don’t forget though, if you allocate with new[], you need to deallocate with delete[] when you’re done with it. Here’s a sketch of what that’d look like:
map<string, double*> array_map;
for (auto it : vector_map){
double* temp_arr = new double[it.second.size()]; // dynamically allocating
std::copy(it.second.begin(), it.second.end(), temp_arr);
array_map.insert({it.first, temp_arr});
}
Just remember, you’ll have to do some housekeeping. When you’re done with this array_map, you’ve got to delete[] those arrays to avoid memory leaks. Something like this:
for (auto it : array_map){
delete[] it.second; // cleaning up
}
Hope this helps you out a bit. C++ can be a bit of a tricky beast with its memory management!