vector的介绍及使用
vector的介绍
vector是表示可变大小数组的序列容器
vector采用连续存储空间来存储元素,类似数组,但本质上vector使用动态分配数组来存储元素
vector的使用
定义
先介绍两个类型
size_type 本质上就是size_t类型
const value_type& val的类型取决于参数T的类型
使用无参构造函数
void test() { vector<int>v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); for (auto e : v) { cout << e << " "; } cout << endl; }
vector iterator的使用
图形展示迭代器中的begin和end
使用
void test() { vector<int>v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); vector<int>::iterator it = v.begin(); while (it != v.end()) { cout << *it << " "; it++; } cout << endl; }
空间增长问题
容量空间 | 接口说明 |
size | 获取数据个数 |
capacity | 获取容量大小 |
empty | 判断是否为空 |
resize | 改变vector的size |
reserve | 改变vector的capacity |
先介绍 vector扩容机制
void testvectorexpend() { size_t sz; vector<int>v; sz = v.capacity(); cout << "making v grow:"; for (int i = 0; i < 100; i++) { v.push_back(i); if (sz != v.capacity()) { sz = v.capacity(); cout << "capacity changed" << sz << endl; } } }
通过运行结果可以得到扩容的大小大概是1.5倍,与string类似,当容量不够使用时,编译器会自动进行扩容来适配所需要的大小
reserve函数
功能:提前预留空间以供使用,如果预留的空间比原有容量小时,会不会进行缩容操作呢?
void test() { vector<int>v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); cout << v.capacity() << endl; v.reserve(10); cout << v.capacity() << endl; v.reserve(3); cout << v.capacity() << endl; }
由运行结果可知:当预留空间比当前容量小时,不会进行缩容操作
resize函数在此情境下同样不会进行缩容操作
增删查改
vector增删查改 | 接口说明 |
push_back | 尾插 |
push_pop | 尾删 |
find | 查找 |
insert | 在pos之前插入val |
erase | 删除pos位置的数据 |
swap | 交换两个vector的数据空间 |
operator[] | 类似数组访问 |
增: push_back,一般不进行头插(效率低);偶尔进行头插insert(iterator begin(),val)
insert函数,插入数据同样借助迭代器
void test() { vector<int>v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); for (auto e : v) { cout << e << " "; } cout << endl; v.insert(v.begin(), 0); v.insert(v.begin() + 5, 5); for (auto e : v) { cout << e << " "; } cout << endl; }
删: pop_back,一般不进行头删(效率低);偶尔进行头删 erase(iterator begin())
void test() { vector<int>v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); vector<int>::iterator it = v.begin(); while (it != v.end()) { cout << *it << " "; it++; } cout << endl; v.pop_back(); it = v.begin(); while (it != v.end()) { cout << *it << " "; it++; } cout << endl; }
查:算法库 find
类模板算法–复用,所有容器均可使用
也是由迭代器实现的
在 vector中查找数字3,若找到在其其前面插入数字30;若没有找到则不做任何操作
void test() { vector<int>v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); for (auto e : v) { cout << e << " "; } cout << endl; vector<int>::iterator it = find(v.begin(), v.end(), 3); if (it != v.end()) { v.insert(it, 30); } for (auto e : v) { cout << e << " "; } cout << endl; }
改:一般配合迭代器使用
``