Seeking union:std::set_union
The two sets and set into the vector.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
set<int> a;
set<int> b;
a.insert(1);
a.insert(3);
a.insert(5);
a.insert(4);
a.insert(9);
a.insert(6);
b.insert(5);
b.insert(6);
b.insert(7);
vector<int> result;
set_union(a.begin(),a.end(),b.begin(),b.end(),inserter(result,result.begin()));
for(int i=0;i<result.size();i++)
{
cout<<result[i]<<" ";
}
return 0;
}
operation result
1 3 4 5 6 7 9
Note : set with ordered, that is to insert elements will automatically sort, but if you need to evaluate vector union, intersection, difference operation, please use the advance sort函数
order.
Intersection of:set_intersection
Vector intersection of two, and the result is retained until the vector.
This time we inserted data has been ordered, and does not require sorting.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> a;
vector<int> b;
a.push_back(1);
a.push_back(3);
a.push_back(5);
a.push_back(6);
a.push_back(7);
a.push_back(10);
b.push_back(5);
b.push_back(6);
b.push_back(7);
vector<int> result;
set_intersection(a.begin(),a.end(),b.begin(),b.end(),inserter(result,result.begin()));
for(int i=0;i<result.size();i++)
{
cout<<result[i]<<" ";
}
return 0;
}
operation result:
5 6 7
Differencing set:set_difference
Differencing the two vector sets, placed in a new vector.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> a;
vector<int> b;
a.push_back(1);
a.push_back(3);
a.push_back(5);
a.push_back(6);
a.push_back(7);
a.push_back(10);
b.push_back(5);
b.push_back(6);
b.push_back(7);
vector<int> result;
set_difference(a.begin(),a.end(),b.begin(),b.end(),inserter(result,result.begin()));
for(int i=0;i<result.size();i++)
{
cout<<result[i]<<" ";
}
return 0;
}
operation result:
1 3 10
Supplements
It should be noted that these three functions and will not help us to complete the 去重
operation, if necessary 去重
, use the unique
function.
Order intersection, for example, the presence of the same element in the vector.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> a;
vector<int> b;
a.push_back(1);
a.push_back(3);
a.push_back(5);
a.push_back(5);
a.push_back(7);
a.push_back(10);
b.push_back(5);
b.push_back(5);
b.push_back(7);
vector<int> result;
set_intersection(a.begin(),a.end(),b.begin(),b.end(),inserter(result,result.begin()));
for(int i=0;i<result.size();i++)
{
cout<<result[i]<<" ";
}
return 0;
}
operation result
5 5 7
If you do not want is equal, for example, by
result.erase(unique(result.begin(),result.end()), result.end());
To resolve.