vector容器的resize和reserve函数 一、resize 1、resize(n) 调整容器的长度大小,使其能容纳n个元素。 如果n小于容器的当前的size,则删除多出来的元素。 否则,添加采用值初始化的元素。 2、 resize(n,t) 多一个参数t,将所有新添加的元素初始化为t。 二、reserve reserver()的用法只有一种:reserve(n) 预...
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);...
vector中存储的元素的地址是连续的 vector对象的地址在运行中未发生改变 使用reserve函数仅改变vector的容量 使用reserve函数后再使用resize函数改变vector的大小
// vector::rbegin/rend#include<iostream>#include<vector>intmain(){std::vector<int>myvector(5);// 5个默认构造整数inti =0; std::vector<int>::reverse_iterator rit = myvector.rbegin();for(; rit != myvector.rend(); ++rit) *rit = ++i; std::cout <<"myvector contains:";for(std::...
myvector.resize(5); 将原来有10个数的vector数组,调整为5个数的长度,多余的数删掉,释放内存。5 < 10 减小数组长度 myvector.resize(8,100); 将5个数长度的vector数组的长度调整为8,不够的数用100来填补,即增加了3个100。8 > 5 增大数组长度,指定填充元素 ...
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::vector<T,Allocator>::swap std::swap(std::vector) std::erase, std::erase_...
容器调用resize()函数后,所有的空间都已经初始化了,所以可以直接访问。 即,一个空的vector被resize(5)之后,这里面就有5个元素了,再push_back的元素是第6个。 reserve()函数只是预分配空间没有初始化,所以不可访问。 resize的两种惯用法 (1)resize(n) ...
resize若 vector 更改容量,则为其全部。否则仅 end() 与被擦除元素。 pop_back被擦除元素及end()。 成员类型 成员类型定义 value_typeT allocator_typeAllocator size_type无符号整数类型(通常是std::size_t) difference_type有符号整数类型(通常是std::ptrdiff_t) ...
2.resize 改变capacity,与size 3.reserve 改变capacity,不改变size 超过size的capacity不可直接访问,可通过push_back追加,若size < capacity, push_back操作不尽心内存分配。 测试代码: #include <stdio.h>#include<iostream>#include<vector>#include<string>voidShowInfo(conststd::string& info,conststd::vector<...
resize则直接调整vector中元素数量。reserve设置的是vector可容纳元素的最大值,而resize操作直接改变实际元素数量。在实际项目开发中,发现vector对象在执行过程中内存地址保持不变,但其内部元素地址可能变化。以以下代码为例进行演示:运行结果如下,展示了vector执行过程中的特点: