Resorter
Resorter

Reputation: 317

Does vector.swap() and vector.erase() free all the allocated memory if the vector is a vector of vectors?

vector<vector<double>> a;
for (int i=0;i<100;i++)
{
    vector<double> v(i+1);
    iota(v.begin(),v.end(),1);
    a.push_back(v);
}
a.erase(a.begin()+10);    
vector<vector<double>>(a).swap(a);

Question 1: is the memory associated to a[10] freed after a.erase()?

Question 2: is the memory associated to all other vectors freed after swap?

Upvotes: 1

Views: 411

Answers (1)

krzaq
krzaq

Reputation: 16421

1) yes, the object (vector<double> here) is destroyed. But it is worth noting that the outer vector (the one you called erase() on) will not change its capacity.

2) yes, it would be emptied. You can also call a.clear() but it won't change your outer vector's capacity.

You can request removal of the unnecessary capacity by calling shrink_to_fit (C++11 and later only), but it's not binding.

Upvotes: 2

Related Questions