宏观定义: a sequence container that encapsulates dynamic size arrays.
与数组的区别: Vectors usually occupy more space than static arrays, because more memory is allocated to handle future growth. This way a vector does not need to reallocate each time an element is inserted, but only when the additional memory is exhausted.
Create a vector containing integers: 声明一个vector变量的语法为vector<T> vec,其中T代表存储的元素类型,vec为vector变量的名字
#include<vector>#include<iostream>usingnamespace std;intmain(){
vector<int> v;// 创建一个整数vector// 用`push_back`方法将元素添加到向量末尾
v.push_back(42);
v.push_back(33);
v.push_back(2);
v.push_back(12);// 可通过[]或at()来访问向量中的元素int x = v[0];// 访问第一个元素int y = v.at(1);// 访问第二个元素
cout << x << endl;
cout << y << endl;// 可用size()方法来获取向量中元素的数量int size = v.size();
cout << size;// 遍历vector:可使用for循环for(auto element : v){
cout<<element<<"\n";}// 使用`pop_back()`方法删除向量中的最后一个元素
v.pop_back();// 遍历vector:可使用for循环for(auto element : v){
cout<<element<<"\n";}// 清空vector:可使用`clear()`方法
v.clear();// 遍历vector:可使用for循环for(auto element : v){
cout<<element<<"\n";}}