std::vector 在析构的时候会自动清理内存,但是在诸如clear()等函数,并不会释放内存。一起来探讨下std::vecor常用的几个清理元素或内存的函数。这些函数分别为: 1 clear() 2 resize() 3 reserve() 4 shrink_to_fit() 5 swap() clear 编写测试用例代码如下: vector<int> vec; for (int i = 0; i ...
classvector:protected_Vector_base<_Tp,_Alloc>explicitvector(size_type __n):_Base(__n,allocator_type()){_M_finish=uninitialized_fill_n(_M_start,__n,_Tp());}template<class_Tp,class_Alloc>class_Vector_base{public:~_Vector_base(){_M_deallocate(_M_start,_M_end_of_storage-_M_start);...
myvector.resize(5); 将原来有10个数的vector数组,调整为5个数的长度,多余的数删掉,释放内存。5 < 10 减小数组长度 myvector.resize(8,100); 将5个数长度的vector数组的长度调整为8,不够的数用100来填补,即增加了3个100。 myvector.resize(12); 将8个数长度的vector数组的长度调整为12,用0默认填补,即...
std::vector<int> vec{1,2,3};std::vector<int>::iterator it; vec.push_back(4);//1,2,3,4vec.emplace_back(5);//1,2,3,4,5it = vec.begin() +1;autor1 = vec.emplace(it,6);//1,6,2,3,4,5 在vec的第一个位置加1(即第二个元素)之前添加一个元素autor2 = vec.insert(r1,7)...
std::vector<T,Allocator>::capacity std::vector<T,Allocator>::shrink_to_fit std::vector<T,Allocator>::clear std::vector<T,Allocator>::insert std::vector<T,Allocator>::emplace std::vector<T,Allocator>::erase std::vector<T,Allocator>::emplace_back std::vector<T,Allocator>::resize std:...
c.resize(num) 重新指定队列的长度。 c.reserve() 保留适当的容量。 c.size() 返回容器中实际数据的个数。 c1.swap(c2) swap(c1,c2) 将c1和c2元素互换。 同上操作。 vector<Elem> c vector<Elem> c1(c2) vector <Elem> c(n) vector <Elem> c(n, elem) ...
reserve方法:功能:用于预先设定vector的容量上限,确保在达到这个容量之前,vector不需要重新分配内存。元素数量:不会改变vector中实际元素的数量。内存地址:通常不会改变vector对象的内存地址,也不会改变已有元素的存储位置。resize方法:功能:直接调整vector的实际元素数量,使其达到指定的值。容量变化:...
address of the element vec[0]: 0x25327c0 address of the element vec[1]: 0x25327c8 在运行过程中有如下特点: vector中存储的元素的地址是连续的 vector对象的地址在运行中未发生改变 使用reserve函数仅改变vector的容量 使用reserve函数后再使用resize函数改变vector的大小...
C++中的std::vector提供两个重要操作:reserve和resize。reserve用于预先设定vector的容量,resize则直接调整vector中元素数量。reserve设置的是vector可容纳元素的最大值,而resize操作直接改变实际元素数量。在实际项目开发中,发现vector对象在执行过程中内存地址保持不变,但其内部元素地址可能变化。以以下代码...
a.clear(); //清空 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 3. 遍历 vector<int> a(10); // for循环 for (int i = 0; i < a.size(); i++) { cout << a[i] << endl; } //迭代器法 for (vector<int> ::iterator iter = a.begin(); iter != a.end(); ...