How to operate set_difference, set_intersection and set_union in c++STL
How to operate c++STL set_difference and set_intersection and set_union, I believe that many inexperienced people are helpless about this, this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.
Several functions of STL algorithm, the condition used is ordered container, so vector can be used after being sorted, set can also be used.
set_difference This is what is found in the first container and not in the second container. set_intersection finds the intersection of two containers, set_union finds the union of two containers.
set_symmetric_difference Find the difference between two containers.
The last time you use it, pay attention to allocating the last container in advance, its size is preferably the sum of the two operation containers, and then you need to resize according to the returned iterator, see the following example.
// set_symmetric_difference example #include // std::cout #include // std::set_symmetric_difference, std::sort #include // std::vector int main () { int first[] = {5,10,15,20,25}; int second[] = {50,40,30,20,10}; std::vector v(10); // 0 0 0 0 0 0 0 0 0 0 std::vector::iterator it; std::sort (first,first+5); // 5 10 15 20 25 std::sort (second,second+5); // 10 20 30 40 50 it=std::set_symmetric_difference (first, first+5, second, second+5, v.begin()); // 5 15 25 30 40 50 0 0 0 0 v.resize(it-v.begin()); // 5 15 25 30 40 50 std::cout