vector 是 STL 提供的 内存连续的可变长度 的数组(亦称列表或向量)数据结构。能够提供线性复杂度的插入和删除,以及常数复杂度的随机访问。

特性

动态分配内存

很多时候我们不能提前开好那么大的空间。尽管我们能知道数据总量在空间允许的级别,但是单份数据还可能非常大,这种时候我们就需要 vector 来把内存占用量控制在合适的范围内。 vector 还支持动态扩容,在内存非常紧张的时候这个特性就能派上用场了。

构造函数

  1. // 创建空 vector
  2. vector<int> v1;
  3. // 创建一个初始长度为 3 的 vector,元素默认值为 0
  4. vector<int> v2(3);
  5. // 创建一个初始长度为 3 的 vector,元素默认值为 2
  6. vector<int> v3(3, 2);
  7. // C++11 初始化列表
  8. vector<int> v4{1, 2, 3, 4};
  9. // 拷贝构造
  10. vector<int> v5(v4);
  11. // 拷贝 v4 的部分内容,也就是 {2, 3}
  12. vector<int> v6(v4.begin() + 1, v4.begin() + 3);

成员函数

元素访问

  • at() 访问指定的元素,同时进行越界检查,越界则抛出异常。
  • operator[] 重载了 [] ,可以像普通数组一样通过 v[index] 访问。
  • front() 返回第一个元素的值。
  • back() 返回最后一个元素的值。
  • data() 返回指向内存中数组第一个元素的指针。

迭代器

  • begin() 返回指向起始的迭代器。
  • end() 返回指向末尾的迭代器。
  • rbegin() 返回指向起始的逆向迭代器。
  • rend() 返回指向末尾的逆向迭代器。

容量

  • empty() 检查容器是否为空。
  • size() 返回容纳的元素数。
  • max_size() 返回容器大小的理论极限,这个值通常会受内存限制。
  • reserve() 预先申请存储空间。(修改 capacity
  • capacity() 返回当前存储空间能够容纳的元素数。
  • shrink_to_fit() 释放未使用的内存减少内存的使用(减小 capacitysize

修改

  • clear() 清空内容。
  • insert() 插入元素。
  • emplace() 原位构造元素。(可以理解为更高效的插入)
  • erase() 删除元素。
  • push_back() 将元素添加到容器末尾。
  • emplace_back() 在容器末尾就地构造元素。
  • pop_back() 移除末元素。
  • resize() 改变容器中可存储元素的个数。(修改 size
  • swap() 交换内容。

二维vector(存储整型)

二维vector可以看做vector里面存储的每个元素类型是vector

初始化

初始化一个5行3列的二维vector

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4. int row = 5;
  5. int col = 3;
  6. vector<vector<int>> v(row,vector<int>(3,0));
  7. system("pause");
  8. return 0;
  9. }

获取行数/列数

  1. vector<vector<int>> v(row,vector<int>(3,0));
  2. v.size(); // 行数
  3. v[0].size(); // 列数

遍历

普通for-i循环

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4. int row = 5;
  5. int col = 3;
  6. vector<vector<int>> v(row,vector<int>(3,0));
  7. for(int i = 0;i < row;i++){
  8. for(int j = 0;j < col;j++){
  9. cout << v[i][j] << " ";
  10. }
  11. cout << endl;
  12. }
  13. system("pause");
  14. return 0;
  15. }

增强for循环

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4. int row = 5;
  5. int col = 3;
  6. vector<vector<int>> v(row,vector<int>(3,0));
  7. for(auto r : v){
  8. for(auto c : r){
  9. cout << c << " ";
  10. }
  11. cout << endl;
  12. }
  13. system("pause");
  14. return 0;
  15. }

迭代器

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4. int row = 5;
  5. int col = 3;
  6. vector<vector<int>> v(row,vector<int>(3,0));
  7. vector<vector<int>>::iterator row_it;
  8. vector<int>::iterator col_it;
  9. for(row_it = v.begin();row_it < v.end();row_it++){
  10. for(col_it = (*row_it).begin();col_it < (*row_it).end();col_it++){
  11. cout << (*col_it) << " ";
  12. }
  13. cout << endl;
  14. }
  15. system("pause");
  16. return 0;
  17. }