标签:erase false vector find https 函数 turn pre tor
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 感谢博主!
【C++】Vector判断元素是否存在,去重,求交集,求并集
标签:erase false vector find https 函数 turn pre tor
原文地址:https://www.cnblogs.com/KMould/p/11837093.html