STL-vector
vector 是C++ 标准模板库(STL)中的一个容器类,它提供了一种动态大小的数组实现。
1.vector的介绍及使用
1. vector是表示可变大小数组的序列容器。
2. 就像数组一样,vector也采用的连续存储空间来存储元素。也就是意味着可以采用下标对vector的元素进行访问,和数组一样高效。但是又不像数组,它的大小是可以动态改变的,而且它的大小会被容器自动处理。
3. 本质讲,vector使用动态分配数组来存储它的元素。当新元素插入时候,这个数组需要被重新分配大小为了增加存储空间。其做法是,分配一个新的数组,然后将全部元素移到这个数组。就时间而言,这是一个相对代价高的任务,因为每当一个新的元素加入到容器的时候,vector并不会每次都重新分配大小。
4. vector分配空间策略:vector会分配一些额外的空间以适应可能的增长,因为存储空间比实际需要的存储空间更大。不同的库采用不同的策略权衡空间的使用和重新分配。但是无论如何,重新分配都应该是对数增长的间隔大小,以至于在末尾插入一个元素的时候是在常数时间的复杂度完成的。
5. 因此,vector占用了更多的存储空间,为了获得管理存储空间的能力,并且以一种有效的方式动态增长。
6. 与其它动态序列容器相比(deque, list and forward_list), vector在访问元素的时候更加高效,在末尾添加和删除元素相对高效。对于其它不在末尾的删除和插入操作,效率更低。比起list和forward_list统一的迭代器和引用更好。
使用STL的三个境界:能用,明理,能扩展 ,那么学习vector,我们也是按照这个方法去学习
2.vector的使用
#include<iostream>
#include<vector>
using namespace std;int main()
{// 初始化方式1:使用初始化列表直接赋值vector<int> v1{ 1, 2, 3 ,4,5,6,7,9 };for (auto num : v1) {cout << num << " ";}cout << endl;// 初始化方式2:创建包含5个0的向量vector<int> v2(5, 0);for (auto num : v2){cout << num << " ";}cout << endl;// 初始化方式3:使用等号加初始化列表vector<int> v3 = { 1, 2, 3 };for (auto num : v3){cout << num << " ";}cout << endl;// 初始化方式4:拷贝构造函数vector<int> v4(v3); for (auto num : v4){cout << num << " ";}cout << endl;// 初始化方式5:使用迭代器范围初始化vector<int> v5(v3.begin(), v3.end());for (auto num : v5){cout << num << " ";}cout << endl;// 尾部插入元素(调用构造函数)v1.push_back(8); for (auto num : v1){cout << num << " ";}cout << endl;// 尾部构造并插入元素(直接构造)v1.emplace_back(9);for (auto num : v1){cout << num << " ";}cout << endl;// 在指定位置插入元素v1.insert(v1.begin() + 2, 20);for (auto num : v1){cout << num << " ";}cout << endl;// 删除尾部元素v1.pop_back();for (auto num : v1){cout << num << " ";}cout << endl;// 删除指定位置元素v1.erase(v1.begin() + 1);for (auto num : v1){cout << num << " ";}cout << endl;// 清空向量v3.clear();for (auto num : v3){cout << num << " "; // 不会输出任何内容}cout << endl;// 访问元素方式1:使用下标运算符(不检查越界)int a = v1[0];cout << a << endl;// 访问元素方式2:使用at方法(检查越界)int b = v1.at(1);cout << b << endl;// 访问第一个元素int front = v1.front(); cout << front << endl;// 访问最后一个元素int back = v1.back();cout << back << endl;// 预分配内存空间v1.reserve(100); // 调整向量大小(新增元素默认初始化)v2.resize(10); // 释放未使用的内存v1.shrink_to_fit();// 使用下标遍历for (size_t i = 0; i < v1.size(); ++i){cout << v1[i] << " ";}cout << endl;// 使用迭代器遍历for (auto it = v1.begin(); it != v1.end(); ++it) {cout << *it << " ";}cout << endl;// 交换两个向量的内容v1.swap(v2);for (auto it = v1.begin(); it != v1.end(); ++it){cout << *it << " ";}cout << endl;// 用迭代器范围赋值v2.assign(v1.begin(), v1.end());for (auto it = v2.begin(); it != v2.end(); ++it){cout << *it << " ";}cout << endl;return 0;
}
capacity的代码在vs和g++下分别运行会发现,vs下capacity是按大概1.5倍增长的,g++是按2倍增长的。这个问题经常会考察,不要固化的认为,vector增容都是2倍,具体增长多少是根据具体的需求定义的。vs是PJ版本STL,g++是SGI版本STL。
vs2019下:
由于本人没有装g++,这里就没有演示结果。
reserve只负责开辟空间,如果确定知道需要用多少空间,reserve可以缓解vector增容的代价缺陷问题。
resize在开空间的同时还会进行初始化,影响size。
3.vector 迭代器失效问题
迭代器的主要作用就是让算法能够不用关心底层数据结构,其底层实际就是一个指针,或者是对指针进行了封装,比如:vector的迭代器就是原生态指针T* 。因此迭代器失效,实际就是迭代器底层对应指针所指向的空间被销毁了,而使用一块已经被释放的空间,造成的后果是程序崩溃(即如果继续使用已经失效的迭代器,程序可能会崩溃)。
对于vector可能会导致其迭代器失效的操作有
(1) 会引起其底层空间改变的操作,都有可能是迭代器失效,比如:resize、reserve、insert、assign、push_back等。
#include <iostream>
using namespace std;
#include <vector>
int main()
{vector<int> v{ 1,2,3,4,5,6 };auto it = v.begin();// 将有效元素个数增加到100个,多出的位置使用8填充,操作期间底层会扩容// v.resize(100, 8);// reserve的作用就是改变扩容大小但不改变有效元素个数,操作期间可能会引起底层容量改变// v.reserve(100);// 插入元素期间,可能会引起扩容,而导致原空间被释放// v.insert(v.begin(), 0);// v.push_back(8);// 给vector重新赋值,可能会引起底层容量改变v.assign(100, 8);/*出错原因:以上操作,都有可能会导致vector扩容,也就是说vector底层原理旧空间被释放掉,而在打印时,it还使用的是释放之间的旧空间,在对it迭代器操作时,实际操作的是一块已经被释放的空间,而引起代码运行时崩溃。解决方式:在以上操作完成之后,如果想要继续通过迭代器操作vector中的元素,只需给it重新赋值即可。*/while (it != v.end()){cout << *it << " ";++it;}cout << endl;return 0;
}
结果图:
2. 指定位置元素的删除操作--erase
#include <iostream>
using namespace std;
#include <vector>
int main()
{int a[] = { 1, 2, 3, 4 };vector<int> v(a, a + sizeof(a) / sizeof(int));// 使用find查找3所在位置的iteratorvector<int>::iterator pos = find(v.begin(), v.end(), 3);// 删除pos位置的数据,导致pos迭代器失效。v.erase(pos);cout << *pos << endl; // 此处会导致非法访问return 0;
}
结图:
rase删除pos位置元素后,pos位置之后的元素会往前搬移,没有导致底层空间的改变,理论上讲迭代器不应该会失效,但是:如果pos刚好是最后一个元素,删完之后pos刚好是end的位置,而end位置是没有元素的,那么pos就失效了。因此删除vector中任意位置上元素时,vs就认为该位置迭代器失效了。
4.vector模拟实现
#include <iostream>
#include <algorithm> // std::move
#include <stdexcept> // std::out_of_range
#include <initializer_list>// 自定义Vector类,模拟STL的vector容器
template <typename T>
class Vector
{
private:T* data = nullptr; // 动态数组,存储元素size_t size = 0; // 当前元素数量size_t capacity = 0; // 已分配的内存容量// 扩容策略:当容量不足时按2倍增长void grow_capacity() {if (capacity == 0) {reserve(1); // 初始容量设为1}else {reserve(capacity * 2); // 容量翻倍}}public:// 类型别名,模仿STL vector的接口using value_type = T;using iterator = T*;using const_iterator = const T*;// -------------------- 构造与析构 --------------------// 默认构造函数Vector() = default;// 初始化列表构造函数Vector(std::initializer_list<T> init) : size(init.size()), capacity(init.size()) {data = new T[capacity];// 复制初始化列表中的元素std::copy(init.begin(), init.end(), data);}// 拷贝构造函数(深拷贝)Vector(const Vector& other) : size(other.size), capacity(other.capacity) {data = new T[capacity];// 逐个复制元素for (size_t i = 0; i < size; ++i) {data[i] = other.data[i];}}// 移动构造函数Vector(Vector&& other) noexcept: data(other.data), size(other.size), capacity(other.capacity) {// 接管资源并将原对象置空other.data = nullptr;other.size = 0;other.capacity = 0;}// 析构函数~Vector() {delete[] data; // 释放动态分配的内存}// -------------------- 赋值运算符 --------------------// 拷贝赋值运算符Vector& operator=(const Vector& other){if (this != &other) {delete[] data; // 释放当前资源// 复制其他Vector的状态size = other.size;capacity = other.capacity;data = new T[capacity];// 逐个复制元素for (size_t i = 0; i < size; ++i) {data[i] = other.data[i];}}return *this;}// 移动赋值运算符Vector& operator=(Vector&& other) noexcept {if (this != &other) {delete[] data; // 释放当前资源// 接管资源并将原对象置空data = other.data;size = other.size;capacity = other.capacity;other.data = nullptr;other.size = 0;other.capacity = 0;}return *this;}// -------------------- 容量操作 --------------------size_t get_size() const { return size; }size_t get_capacity() const { return capacity; } // 新增capacity访问方法bool empty() const { return size == 0; }// 预分配内存void reserve(size_t new_cap) {if (new_cap <= capacity) return; // 无需缩小容量T* new_data = new T[new_cap];// 移动现有元素到新内存for (size_t i = 0; i < size; ++i){new_data[i] = std::move(data[i]);}delete[] data; // 释放旧内存data = new_data;capacity = new_cap;}// 将容量缩小到元素数量void shrink_to_fit() {if (size < capacity){capacity = size;T* new_data = new T[capacity];// 移动现有元素到新内存for (size_t i = 0; i < size; ++i) {new_data[i] = std::move(data[i]);}delete[] data; // 释放旧内存data = new_data;}}// -------------------- 元素访问 --------------------// 非const版本,允许修改元素T& operator[](size_t pos) {return data[pos];}// const版本,用于const对象const T& operator[](size_t pos) const {return data[pos];}// 带边界检查的元素访问T& at(size_t pos) {if (pos >= size) throw std::out_of_range("Vector::at");return data[pos];}// 访问第一个元素T& front() { return data[0]; }// 访问最后一个元素T& back() { return data[size - 1]; }// -------------------- 迭代器支持 --------------------iterator begin() { return data; }iterator end() { return data + size; }const_iterator begin() const { return data; }const_iterator end() const { return data + size; }// -------------------- 修改操作 --------------------// 清空所有元素(不释放内存)void clear(){size = 0; // 注意:不释放内存,仅重置大小}// 添加元素(左值引用版本)void push_back(const T& value) {if (size >= capacity) grow_capacity();data[size++] = value;}// 添加元素(右值引用版本,支持移动语义)void push_back(T&& value){if (size >= capacity) grow_capacity();data[size++] = std::move(value);}// 就地构造元素template <typename... Args>void emplace_back(Args&&... args) {if (size >= capacity) grow_capacity();// 原地构造对象,避免不必要的拷贝或移动new (data + size) T(std::forward<Args>(args)...);size++;}// 删除最后一个元素void pop_back() {if (size > 0) size--;}// 在指定位置插入元素iterator insert(iterator pos, const T& value) {size_t offset = pos - begin(); // 计算插入位置的偏移量if (size >= capacity) grow_capacity();// 向后移动元素为新元素腾出空间for (size_t i = size; i > offset; --i){data[i] = std::move(data[i - 1]);}data[offset] = value;size++;return begin() + offset;}// 删除指定位置的元素iterator erase(iterator pos) {size_t offset = pos - begin(); // 计算删除位置的偏移量// 向前移动元素覆盖被删除的元素for (size_t i = offset; i < size - 1; ++i) {data[i] = std::move(data[i + 1]);}size--;return begin() + offset;}
};// 测试Vector类的功能
#include <iostream>
#include <vector>
#include <cassert>void test_vector()
{// -------------------- 基础构造与内存管理 --------------------{Vector<int> v;assert(v.get_size() == 0);assert(v.get_capacity() == 0);v.push_back(42);assert(v.get_size() == 1);assert(v.get_capacity() >= 1); // 首次扩容到1} // 此处应无内存泄漏// -------------------- 初始化列表构造 --------------------{Vector<int> v{ 1, 2, 3 };assert(v.get_size() == 3);assert(v[0] == 1 && v[1] == 2 && v[2] == 3);}// -------------------- 深拷贝测试 --------------------{Vector<int> v1;v1.push_back(10);v1.push_back(20);Vector<int> v2 = v1; // 拷贝构造v2.push_back(30);assert(v1.get_size() == 2);assert(v2.get_size() == 3);assert(v2[2] == 30);}// -------------------- 移动语义测试 --------------------{Vector<int> v1{ 1, 2, 3 };Vector<int> v2 = std::move(v1);assert(v1.get_size() == 0); // 原对象被置空assert(v2.get_size() == 3);assert(v2[2] == 3);}// -------------------- 动态扩容测试 --------------------{Vector<int> v;for (int i = 0; i < 100; ++i) {v.push_back(i);}assert(v.get_size() == 100);assert(v.get_capacity() >= 100);assert(v[99] == 99);}// -------------------- shrink_to_fit测试 --------------------{Vector<int> v;v.reserve(100);v.push_back(1);v.shrink_to_fit();assert(v.get_capacity() == 1);}// -------------------- 迭代器测试 --------------------{Vector<int> v{ 10, 20, 30 };size_t sum = 0;for (auto it = v.begin(); it != v.end(); ++it){sum += *it;}assert(sum == 60);}// -------------------- insert/erase测试 --------------------{Vector<int> v{ 1, 3 };auto it = v.insert(v.begin() + 1, 2); // 插入中间assert(v.get_size() == 3);assert(v[1] == 2);it = v.erase(v.begin()); // 删除第一个元素assert(v.get_size() == 2);assert(v[0] == 2);}// -------------------- 异常安全测试 --------------------{Vector<int> v;bool caught = false;try {v.at(0); // 访问空vector}catch (const std::out_of_range&) {caught = true;}assert(caught);}std::cout << "All STL-style vector tests passed!\n";
}int main()
{test_vector();return 0;
}