简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM