Set's keys are automatically sorted, corresponding to the convergence of the set difference can be used to this ordered characteristics, time complexity is O (m+n), m,n respectively two container size
1.set_union can be used to find the set of two sets, which is a stable operation because the relative position between elements does not change.
The source code is as follows:
Template <class inputiterator1,class inputiterator2,class outputiterator> outputiterator set_union
( InputIterator1 First1,inputiterator1 last1,
InputIterator2 first2,inputiterator2 last2,
outputiterator Result)
{while
(First1!=last1&&first2!=last2)
{
if (*first1<*first2)
{
* Result=*first1;
++first1;
}
else if (*first1>*first2)
{
*result=*first2;
++first2;
}
else //equal situation
{
*result=*first1;
++first1;
++first2;
}
++result;
}
return copy (First2,last2,copy (First1,last1,result));
2.set_intersection can be used to find the intersection of two sets
The source code is as follows:
Template <class inputiterator1,class inputiterator2,class outputiterator >
outputiterator set_intersection (InputIterator1 first1,inputiterator1 Last1,
InputIterator2 First2,inputiterator2 last2,
outputiterator result)
{while
(first1!=last1&& First2!=last2)
{
if (*first1<*first2)
{
++first1;
}
else if (*first1>*first2)
{
++first2
}
else
{ //*first1==*first2, this element is an element of intersection
*result=*first1;
++first1;
++first2;
++result
}
}
return result;
}
3.set_diference is used to find the difference set of two sets
The source code is as follows:
Template <class inputiterator1,class inputiterator2,class outputiterator> outputiterator set_difference
( InputIterator1 First1,inputiterator1 last1,
InputIterator2 first2,inputiterator2 last2,
outputiterator Result)
{while
(First1!=last1&&first2!=last2)
{
if (*first1<*first2) //*first1 <*first2, this element is the element of the difference set
{
*result=*first1;
++first1;
++result;
}
else if (*first1>*first2)
++first2;
else
{
++first1;
++first2
}
}
return copy (First1,last1,result);
}
Simple test:
# include <iostream>
# include <cstdlib>
# include <set> # include
<algorithm>
# include <vector>
using namespace std;
int main ()
{
set<int> s1,s2;
S1.insert (1);
S1.insert (2);
S1.insert (3);
S2.insert (2);
S2.insert (3);
S2.insert (4);
Set<int>::iterator Iter1=s1.begin ();
Set<int>::iterator iter2=s1.end ();
Set<int>::iterator Iter3=s2.begin ();
Set<int>::iterator iter4=s2.end ();
vector<int> Res (10,0);
Vector<int>::iterator iter;
Iter=set_union (Iter1,iter2,iter3,iter4,res.begin ()); and set
//iter=set_intersection (Iter1,iter2,iter3,iter4,res.begin ());//Intersection
//iter=set_difference (Iter1, Iter2,iter3,iter4,res.begin ()); Difference set
res.resize (Iter-res.begin ());
For (Iter=res.begin (); Iter!=res.end (); ++iter)
{
cout<<*iter<<endl;
}
System ("pause");
return 0;
}