[C++] Determine whether the element is in the vector, deduplicate the vector, and find the intersection and union of the two vectors

#include < iostream> 
#include < vector> 
#include < algorithm>  // sort function, intersection and complement function 
#include < iterator>  // iterator used for intersection and complement 
using  namespace std;

//打印容器vector
void print_vector(vector<int> v){
    if(v.size()>0){
        cout<<"{";  
        for(int i=0;i<int(v.size());i++){  
            cout<<v[i]<<",";  
        }  
        cout<<"\b}";  
    }
    else{
        cout<<"{}";
    }
}

// Deduplication of elements in the container vector 
vector< int > unique_element_in_vector(vector< int > v){
    vector<int>::iterator vector_iterator;
    sort(v.begin(),v.end());
    vector_iterator = unique(v.begin(),v.end());
    if(vector_iterator != v.end()){
        v.erase(vector_iterator,v.end());
    }
    return v;
}

// Two vectors to find the intersection 
vector< int > vectors_intersection(vector< int > v1,vector< int > v2){
    vector<int> v;
    sort(v1.begin(),v1.end());   
    sort(v2.begin(),v2.end());   
    set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集 
    return v;
}

// The union of two vectors 
vector< int > vectors_set_union(vector< int > v1,vector< int > v2){
    vector<int> v;
    sort(v1.begin(),v1.end());   
    sort(v2.begin(),v2.end());   
    set_union(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v));//求交集 
    return v;
}

// Determine whether an element of vector exists 
bool is_element_in_vector(vector< int > v, int element){
    vector<int>::iterator it;
    it=find(v.begin(),v.end(),element);
    if (it!=v.end()){
        return true;
    }
    else{
        return false;
    }
}

int main(){
    vector<int> v1,v2,v;
    v1.push_back(22);v1.push_back(22);v1.push_back(23);v2.push_back(23);v2.push_back(24);
    cout << " Is there an element 1 in v1? " <<is_element_in_vector(v1, 1 )<< endl;
    cout << " De -duplicate v1: " ;
    v1=unique_element_in_vector(v1);
    print_vector(v1);
    cout<<endl;
    cout << " Seek the intersection of v1 and v2: " ;
    v=vectors_intersection(v1,v2);
    print_vector(v);
    cout<<endl;
    cout << " Seek the union of v1 and v2: " ;
    v=vectors_set_union(v1,v2);
    print_vector(v);
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324734329&siteId=291194637