I have a 2D vector, and I want all the int values to be replaced by zeros.
Although this code seems to work, I was wondering:
Do I needed to delete the old vector before reassigning it (at line 5), since there is a copy of std::vector<int> stored in line?
Is it the best way to replace values (using iterators)?
Code:
for (std::vector< std::vector<int> >::iterator it = data.begin(); it != data.end(); ++it)
{
std::vector<int> line = *it;
std::fill(line.begin(), line.end(), 0);
*it = line; // line 5
}
I want to avoid memory leaks.
You don't need to delete anything in your code sice you didn't create something with new.
If you want too do all this in a single line you can use std::for_each and std::fill:
#include <algorithm>
#include <vector>
std::vector<std::vector<int>> a;
// set every element in two dimensional vector to 5
std::for_each(a.begin(), a.end(), [](std::vector<int> &x){std::fill(x.begin(), x.end(), 5);});
Addendum related to your comment:
Yes, your original vector is stored on the stack. Since you don't pass a custom allocator, the vector will use the std::allocator to allocate its elements (which in your case are vectors of int). The std::allocator allocates these elements in dynamic memory aka the heap but you don't need to worry about freeing or deleting this memory because it is handeled by the internals of the vector. This means that the memory is deleted at the latest if the destructor of the vector is called (e.g. because it goes out of scope) or possibly earlier if you change the size of the vector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With