Union, intersection, and difference set of set in stl
The set key is automatically sorted, and the corresponding intersection of the Union set difference sets can all use this ordered feature. The time complexity is O (m + n), m, n is the size of the two containers.
1. set_union can be used to calculate the union of two sets. It is a stable operation because the relative positions between elements do not change.
The source code is as follows:
Template
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 case {* result = * first1; ++ first1; ++ first2 ;}++ result ;}return copy (first2, last2, copy (first1, last1, result ));}
2. set_intersection can be used to calculate the intersection of two sets.
The source code is as follows:
Template
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, which is the intersection element * result = * first1; ++ first1; ++ first2; ++ result ;}} return result ;}
3. set_diference is used to calculate the difference set of two sets.
The source code is as follows:
Template
OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) {while (first1! = Last1 & first2! = Last2) {if (* first1 <* first2) // * first1 <* first2, which 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
# Include
# Include
# Include
Using namespace std; int main () {set
S1, s2; s1.insert (1); s1.insert (2); s1.insert (3); s2.insert (2); s2.insert (3); s2.insert (4); set
: Iterator iter1 = s1.begin (); set
: Iterator iter2 = s1.end (); set
: Iterator iter3 = s2.begin (); set
: Iterator iter4 = s2.end (); vector
Res (10, 0); vector
: Iterator iter; iter = set_union (iter1, iter2, iter3, iter4, res. begin (); // Union // 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 <