[C ++] Vector element determines whether there is, deduplication, intersection of, and requirements set

. 1 #include <the iostream>
 2 #include <Vector>
 . 3 #include <algorithm> // Sort functions, and cross-complementary function 
. 4 #include <Iterator> // intersection and used to complement the iterator 
. 5  the using  namespace STD;
 . 6  
7  // prints the container Vector 
. 8  void print_vector (Vector < int > V)
 . 9  {
 10      IF (v.size ()> 0 )
 . 11  {
 12 is          COUT << " { " ;  
 13 is          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>26v)
 {
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 is      Sort (v2.begin (), v2.end ());   
 53 is      set_union (v1.begin (), v1.end (), v2.begin ( ), v2.end (), back_inserter (V)); // intersection of 
54 is      return V;
 55  }
 56 is  
57 is  // determines whether there is an element of the vector 
58  BOOL is_element_in_vector (vector < int > V, int element)
 59  {
 60      Vector < int > :: Iterator IT;
 61 is      IT = Find (v.begin (), v.end (), Element);
 62 is      IF (! IT = v.end ())
 63 is  {
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 << " for weight v1 to: " ;
 77      v1 = unique_element_in_vector (v1);
 78      print_vector (v1);
 79      COUT << endl;
 80      COUT << " seek v1 and v2 intersection: " ;
 81      V = vectors_intersection (v1, v2);
 82      print_vector (V);
 83      COUT << endl;
 84      COUT << " seek v1 and v2 and set: " ;
 85      V = vectors_set_union (v1, v2);
86     print_vector(v);
87     return 0;
88 }

 

Transfer: https: //www.cnblogs.com/mayouyou/p/8921598.html thank bloggers!

Guess you like

Origin www.cnblogs.com/KMould/p/11837093.html