转自https://blog.csdn.net/wangshubo1989/article/details/50359750
现在介绍一个方法,std::vector::clear(),这可以清楚掉向量的元素,但是不能释放内存
Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.
看清楚了吗,英文中提到的是size=0,而非capacity。写程序验证一些:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
cout << "size:" << v.size() << endl;
cout << "capacity:" << v.capacity() << endl;
v.clear();
cout << "after clear size:" << v.size() << endl;
cout << "after clear capacity:" << v.capacity() << endl;
return 0;
}
//输出
size:5
capacity:6
after clear size:0
after clear capacity:6
可以发现使用clear可以清除掉向量的元素,但是仍会为向量保留相应的空间,使用swap则会把保留的空间也给删除掉,当向量用指针表示时,还可以使用delete
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
cout << "size:" << v.size() << endl;
cout << "capacity:" << v.capacity() << endl;
vector<int>().swap(v);
cout << "after swap size:" << v.size() << endl;
cout << "after swap capacity:" << v.capacity() << endl;
return 0;
}
//输出:
size:5
capacity:6
after swap size:0
after swap capacity:0
另一种释放向量内存的方法是
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
cout << "size:" << v.size() << endl;
cout << "capacity:" << v.capacity() << endl;
v.clear();
v.shrink_to_fit();
cout << "after swap size:" << v.size() << endl;
cout << "after swap capacity:" << v.capacity() << endl;
return 0;
}
//输出:
size:5
capacity:6
after swap size:0
after swap capacity:0