STL's built-in set operations set_union and set_intersection are so easy to find intersection and union! !

Dynamic array vector

Note:
1: Before finding the union and intersection, you need to sort the two arrays (both int or vector), otherwise the result will be wrong.
2: The size of the vector needs to be defined , otherwise the result may not be obtained

Union set_union( ) :

int main()
{
    
    
    int a[4]={
    
    1,2,3,4}; //已经有序,若无序,需要排序!
    int b[4]={
    
    2,3,4,5};
    vector<int> c(8);  //需要定义大小
		
	set_union(a,a+4,b,b+4,c.begin()); //并集
	
	for(auto x:c){
    
    
		cout<<x<<" ";
	}
    return 0;
}

operation result:
Insert picture description here


Intersection set_intersection( ) :

int main()
{
    
    
    int a[4]={
    
    1,2,3,4}; //已经有序,若无序,需要排序!
    int b[4]={
    
    2,3,4,5};
    vector<int> c(8); //需要定义大小
		
	set_intersection(a,a+4,b,b+4,c.begin()); //交集
	
	for(auto x:c){
    
    
		cout<<x<<" ";
	}
    return 0;
}

operation result:
Insert picture description here


If you don't want the following 0 to appear, take the intersection as an example:

int main()
{
    
    
    int a[4]={
    
    1,2,3,4}; //已经有序,若无序,需要排序!
    int b[4]={
    
    2,3,4,5};
    vector<int> c(8);
		
	vector<int>::iterator it=set_intersection(a,a+4,b,b+4,c.begin()); //交集 返回位置到it
	
	cout<<it-c.begin()<<endl;  //交集中元素个数
	
	for(int i=0;i<it-c.begin();i++) //输出这些元素
		cout<<c[i]<<" ";
    return 0;
}

operation result:

Insert picture description here


Set

The difference between a set and a vector is:
1: No sorting, because the set itself is ordered and non-repetitive
2: The fifth parameter of set_union and set_intersection isinserter(c,c.begin() )

Union set_union( ) :

int main()
{
    
    
    set<int> a,b,c;
	for(int i=1;i<5;i++) //a: 1 2 3 4 
		a.insert(i);
		
	for(int i=2;i<6;i++) //b: 2 3 4 5
		b.insert(i);
		
	set_union(a.begin(),a.end(),b.begin(),b.end(),inserter(c,c.begin())); //并集
	
	for(auto x:c){
    
    
		cout<<x<<" ";
	}
    return 0;
}

operation result:
Insert picture description here


Intersection set_intersection( ) :

int main()
{
    
    
    set<int> a,b,c;
	for(int i=1;i<5;i++) //a: 1 2 3 4 
		a.insert(i);
		
	for(int i=2;i<6;i++) //b: 2 3 4 5
		b.insert(i);
		
	set_intersection(a.begin(),a.end(),b.begin(),b.end(),inserter(c,c.begin())); //交集
	
	for(auto x:c){
    
    
		cout<<x<<" ";
	}
    return 0;
}

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45260385/article/details/108385987