[C++] std::vector 使用


什么是vector. 一個封裝良好的變長數組,是同一種類型的對象的集合,每個對象都有一個對應的整數索引值。

 

vector的使用樣例:

1.需要#include <vector>

2.使用std聲明std::vector

3.使用vector<Type> vec() 聲明vector的容量大小(聲明3個單位的容量,vec(3),執行vec[4] = 3,報錯,越界錯誤)

  創建vector對象,vector<int> vec;

4.尾部插入數字:vec.push_back(a);

5.使用下標訪問元素,cout<<vec[0]<<endl;記住下標是從0開始的。

6.使用迭代器訪問元素.

vector<int>::iterator it;
for(it=vec.begin();it!=vec.end();it++)
    cout<<*it<<endl;

7.插入元素:    vec.insert(vec.begin()+i,a);在第i+1個元素前面插入a;

8.刪除元素:    vec.erase(vec.begin()+2);刪除第3個元素

  vec.erase(vec.begin()+i,vec.end()+j);刪除區間[i,j-1];區間從0開始

9.向量大小:vec.size();

10.清空:vec.clear();

 

執行:

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 
 5 using namespace std;
 6 
 7 const int NUM = 5;
 8 
 9 int main()
10 {
11     vector<int> vec1(NUM);
12     vector<int> vec2(NUM);
13 
14     int i;
15     for(int i = 0; i < NUM; i++)
16     {
17         vec1[i] = i * 5;
18         vec2[i] = i + 3;
19     }
20 
21     for(int i = 0; i < NUM; i++)
22     {
23         cout<<"vec1:"<<vec1[i]<<"\tvec2:"<<vec2[i]<<endl;
24     }
25     return 0;
26 }

結果:

1 vec1:0    vec2:3
2 vec1:5    vec2:4
3 vec1:10    vec2:5
4 vec1:15    vec2:6
5 vec1:20    vec2:7

 

對vec的基本操作:

 1 #include<iostream>
 2 #include<vector>
 3 #include<algorithm>
 4 
 5 using namespace std;
 6 
 7 void printVector(vector<int> vec)
 8 {
 9     for (int i = 0; i < vec.size(); i++)
10     {
11         cout<<vec[i]<<"   ";
12     }
13     cout<<endl;
14 }
15 
16 bool compare(int &a, int &b)
17 {
18     return a>b;
19 }
20 
21 int main()
22 {
23     vector<int> vec;
24 
25     cout<<"vector size():"<<vec.size()<<endl;
26     for (int i = 0; i < 10; i++)
27     {
28         vec.push_back(i);  //vec尾部壓入i數據
29     }
30     cout<<"vector size():"<<vec.size()<<endl;
31 
32     printVector(vec);
33 
34     //刪除第一個元素
35     vec.erase(vec.begin());
36     printVector(vec);
37 
38     vec.insert(vec.begin(),23);  //在vec的頭部插入23
39     vec.insert(vec.end()-1,4,44);  //在vec的倒數第二個的數后面插入4個44
40     printVector(vec);
41 
42     //獲取指定位置的元素
43     cout<<"vec.at(0) ->"<<vec.at(0)<<endl;
44     cout<<"vec.at(1) ->"<<vec.at(1)<<endl;
45 
46     cout<<"vec.front() ->"<<vec.front()<<endl;  //vec 第一個元素
47     cout<<"vec.back() ->"<<vec.back()<<endl;  //vec 最后一個元素
48 
49     cout<<"翻轉之前:"<<endl;
50     printVector(vec);
51     reverse(vec.begin(), vec.end());
52     cout<<"翻轉之后:"<<endl;
53     printVector(vec);
54     
55     sort(vec.begin(),vec.end());
56     cout<<"排序之后:"<<endl;
57     printVector(vec);
58 
59     cout<<"逆序排序:"<<endl;
60     sort(vec.begin(),vec.end(),compare);
61     printVector(vec);
62 
63     int v;
64     cin>>v;
65     return 0;
66 }

結果:

 

使用reverse, sort函數,需要頭文件#include<algorithm>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM