您的位置:首页 > 编程语言

STL-vector清空的几种方法加代码梳理

2018-12-09 23:38 302 查看

STL-vector清空的几种方法加代码梳理

在做行人检测的项目(HOG+SVM方法)时,因为要计算每幅图像的hog描述子向量,通过调用hog的compute方法,需要传入一个描述子向量:

HOGDescriptor hog;
vector<float> descriptors;
hog.compute(src/*inputImage*/, descriptors, Size(8,8)/*stride of detection window*/);

在每次运行hog.compute()方法后,本次循环结束,需要释放本次循环声明的变量,并析构他的内存空间,也就是析构descriptors向量的空间,就在这个时候程序莫名报错了,跟踪发现是vector析构时出错,在声明descriptors时给定分配空间大小后问题解决:

HOGDescriptor hog;
vector<float> descriptors(4000)//64*128图像的默认hog特征参数的描述子向量长度为3780;
hog.compute(src/*inputImage*/, descriptors, Size(8,8)/*stride of detection window*/);

这引发了我对vector如何清空其内存空间的思考,梳理总结如下四种清空方法:
STL清空代码总结在GitHub:
https://github.com/Rayholle/LeetCode-Newcoder/blob/master/STL/vector清空的几种方法.cpp

vector<int> vetInt;
for(int i = 0; i < 500; i++){
vetInt.emplace_back(i);
}
int capacity = vecInt.capacity();   //512
int size = vecInt.size();                  //500

1、’='赋值操作符重载,赋值新的数组

此时分配空间大小没有变化,数据尺寸变化,说明空间没有回收

vecInt = {1,2,3,4,5,6,7,8,9,0);
int capacity = vecInt.capacity();   //512
int size = vecInt.size();           //10

2、vector的clear()方法

此方法清空元素,空间未回收

vecInt.clear();
int capacity = vecInt.capacity();   //512
int size = vecInt.size();           //0

3、vector的erase()方法

此方法清空元素,不回收空间

for(auto it = vecInt.begin(); it!=vecInt.end(); it++)
{
it = vecInt.erase(iter);//erase自动返回下一个元素的迭代器
}
int capacity = vecInt.capacity();   //512
int size = vecInt.size();           //0

4、swap()的方法

此方法可以既清空元素,也可以将vecInt数组内存空间回收

vector<int>().swap(vecInt);
int capacity = vecInt.capacity();   //0
int size = vecInt.size();           //0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: