vector數組


1.Vector數組可以認為是大小的數組。

2.它可以實現排序,函數是sort(v.begin(),v.end() 。

3.它可以實現二分查找功能,函數是lower_bound(v.begin(),v.end(),x)。查找的是值x,返回第一個大於或者等於小的值的指針。如果查找返回的是指針v.end()或者發現*it!=x那么容器里沒有x這個數。

4.unique函數可以刪除有序數組中的重復元素。頭文件<algorithm>

unique(num,mun+n)返回的是num去重后的尾地址,之所以說比不真正把重復的元素刪除,其實是,該函數把重復的元素一到后面去了,然后依然保存到了原數組中,然后返回去重后最后一個元素的地址,因為unique去除的是相鄰的重復元素,所以一般用之前都會要排一下序。

1 #include <iostream>
2 #include <algorithm>
3 using namespace std;
4 int main(){
5     int num[] = {1,1,2,2,3,4,4,4,5,5,5};
6     unique(num,num + 11);
7     for(int i = 0 ; i < 11 ; i++) cout << num[i] << endl;
8 }

5.a.size()讀取vector數組的大小,a.resize()改變大小。

6.a.push_back()向尾部添加元素,a.pop_back()刪除尾部元素。

實例代碼:

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <vector>
 5 #include <string>
 6 #include <algorithm>
 7 #include <cmath>
 8 using namespace std;
 9 int n,m;
10 int main(){
11     vector<int> v;
12     int Case = 0;
13     while(scanf("%d%d",&n,&m) != EOF &&(n || m)){
14         v.clear();
15         int x;
16         for(int i = 0 ; i < n ; i++){
17             scanf("%d",&x);
18             v.push_back(x);
19         }
20         sort(v.begin(),v.end());
21         printf("CASE# %d:\n",++Case);
22         for(int i = 0 ; i < m ; i++){
23             scanf("%d",&x);
24             vector<int>::iterator it = lower_bound(v.begin(),v.end(),x);
25             if(it == v.end())
26                 printf("%d not found\n",x);
27             else{
28                 if(*it == x)
29                     printf("%d found at %d\n",x,it - v.begin() + 1);
30                 else
31                     printf("%d not found\n",x);
32             }
33         }
34     }
35     return 0;
36 }
View Code

 


免責聲明!

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



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