有序数据结构的交与并

发布时间 2023-11-17 12:03:12作者: 我微笑不代表我快乐

需要注意:
1:求并集和交集前,需要将两个数组先进行排序 (int 或者 vector都需要),否则结果有误

2:需要定义vector的size,否则可能无法得到结果

 

vector的并

#include <bits/stdc++.h>
using namespace std;
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;
}

 

vector的交

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a[4]={1,2,3,4}; //已经有序,若无序,需要排序!
    int b[4]={2,3,4,5};
    vector<int> c(8);
    auto 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;
}

  

 

set 的并

#include <bits/stdc++.h>
using namespace std;
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;
}

  

set 的交

#include <bits/stdc++.h>
using namespace std;
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;
}