【C++】Vector判斷元素是否存在,去重,求交集,求並集

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm> //sort函數、交併補函數
 4 #include <iterator> //求交併補使用到的迭代器
 5 using namespace std;  6 
 7 //打印容器vector
 8 void print_vector(vector<int> v)  9 { 10     if(v.size()>0) 11 { 12         cout<<"{"; 13         for(int i=0;i<int(v.size());i++) 14 { 15             cout<<v[i]<<","; 16  } 17         cout<<"\b}"; 18  } 19     else{ 20         cout<<"{}"; 21  } 22 } 23 
24 //容器vector中元素的去重
25 vector<int> unique_element_in_vector(vector<int> v) 26 { 27     vector<int>::iterator vector_iterator; 28  sort(v.begin(),v.end()); 29     vector_iterator = unique(v.begin(),v.end()); 30     if(vector_iterator != v.end()) 31 { 32  v.erase(vector_iterator,v.end()); 33  } 34     return v; 35 } 36 
37 //兩個vector求交集
38 vector<int> vectors_intersection(vector<int> v1,vector<int> v2) 39 { 40     vector<int> v; 41  sort(v1.begin(),v1.end()); 42  sort(v2.begin(),v2.end()); 43     set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集 
44     return v; 45 } 46 
47 //兩個vector求並集
48 vector<int> vectors_set_union(vector<int> v1,vector<int> v2) 49 { 50     vector<int> v; 51  sort(v1.begin(),v1.end()); 52  sort(v2.begin(),v2.end()); 53     set_union(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集 
54     return v; 55 } 56 
57 //判斷vector的某一元素是否存在
58 bool is_element_in_vector(vector<int> v,int element) 59 { 60     vector<int>::iterator it; 61     it=find(v.begin(),v.end(),element); 62     if (it!=v.end()) 63 { 64         return true; 65  } 66     else{ 67         return false; 68  } 69 } 70 
71 int main() 72 { 73     vector<int> v1,v2,v; 74     v1.push_back(22);v1.push_back(22);v1.push_back(23);v2.push_back(23);v2.push_back(24); 75     cout<<"v1是否存在1這個元素?"<<is_element_in_vector(v1,1)<<endl; 76     cout<<"對v1去重:"; 77     v1=unique_element_in_vector(v1); 78  print_vector(v1); 79     cout<<endl; 80     cout<<"求v1與v2的交集:"; 81     v=vectors_intersection(v1,v2); 82  print_vector(v); 83     cout<<endl; 84     cout<<"求v1與v2的並集:"; 85     v=vectors_set_union(v1,v2); 86  print_vector(v); 87     return 0; 88 }

 

轉自:https://www.cnblogs.com/mayouyou/p/8921598.html 感謝博主!html

相關文章
相關標籤/搜索