參考鏈接:https://www.geeksforgeeks.org/vector-in-cpp-stl/
Vector是一種簡單高效的容器,可以動態調整所佔用的內存空間
應用:
1.初始化
vector<int>v;
2.迭代器
begin():返回vector中第一個元素
end():返回vector中最後一個元素
rbegin():返回vector中最後一個元素
rend():返回vector中第一個元素
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int>v;
for(int i=1;i<=5;i++)
v.push_back(i);
printf("Output of begin and end: ");
for(auto i=v.begin();i!=v.end();i++)
cout<<*i<<" ";
printf("\nOutput of rbegin and rend: ");
for(auto i=v.rbegin();i!=v.rend();i++)
cout<<*i<<" ";
return 0;
}
Output:
Output of begin and end: 1 2 3 4 5
Output of rbegin and rend: 5 4 3 2 1
3.容量
size():返回元素的個數
max_size():返回vector可以存儲最大元素的個數(不常用)
resize(n):調整vector大小,使其包含n個元素
empty():判斷vector是否爲空,1爲空
4.元素訪問
front():返回第一個元素的引用
back():返回最後一個元素的引用
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int>v;
for(int i=1;i<=5;i++)
v.push_back(i);
printf("Output of front: ");
cout<<v.front();
printf("\nOutput of back: ");
cout<<v.back();
return 0;
}
Output
Output of front: 0
Output of back: 5
5.修飾符
push_back():向末尾添加新元素
pop_back():刪除末尾元素
加粗樣式