1 //vector的添加數據 2 void push_back(數據) 向vector 尾部添加一個數據data 3 v.insert(v.begin(),9); 在v.begin()之前 插入一個數據 4 v.insert(v.begin(),10,1);在v.begin()之前 插入10個1 ,第一個參數是iterator ,第二個參數是一個序列list n=10 val=1 5 v.insert(v.begin()+5,v.begin()+1,v.begin()+3);在迭代器指向的begin+5位置之前,插入序列 [v.begin()+1,v.begin()+3 )之間的數據
代碼:
1 #include <iostream> 2 #include<vector> 3 #include<iterator> 4 //#include<bits/stdc++.h> 5 using namespace std; 6 void show(vector<int>& v){ 7 for(int i=0;i<(int)v.size();i++){ 8 cout<<v[i]<<" "; 9 } 10 cout<<endl; 11 } 12 int main() 13 { 14 vector<int> v; 15 int data; 16 cin>>data;//5 17 v.push_back(data); 18 v.insert(v.begin(),10,1);//插入10個1 19 show(v);//1 1 1 1 1 1 1 1 1 1 5 20 v.insert(v.begin(),1,6);//插入1 個6 21 show(v);//6 1 1 1 1 1 1 1 1 1 1 5 22 v.insert(v.begin(),9);//插入一個9 23 show(v);9 6 1 1 1 1 1 1 1 1 1 1 5 24 vector<int> vt(v); 25 v.insert(v.begin()+5,v.begin(),v.begin()+2);//在第6個位置插入 [0,2) 1,2兩個數據 26 show(v); 27 return 0; 28 }
輸入:
5
輸出:
1 1 1 1 1 1 1 1 1 1 1 5 2 6 1 1 1 1 1 1 1 1 1 1 5 3 9 6 1 1 1 1 1 1 1 1 1 1 5 4 9 6 1 1 1 6 1 1 1 1 1 1 1 1 5