Library: Algorithms
Function
A basic set operation (algorithm) for constructing a sorted symmetric difference
#include <algorithm> namespace std { template <class InputIterator1, class InputIterator2, class OutputIterator> OutputIterator set_symmetric_difference(InputIterator1 start1, InputIterator1 finish1, InputIterator2 start2, InputIterator2 finish2, OutputIterator result); template <class InputIterator1, class InputIterator2, class OutputIterator, class Compare> OutputIterator set_symmetric_difference(InputIterator1 start1, InputIterator1 finish1, InputIterator2 start2, InputIterator2 finish2, OutputIterator result, Compare comp); }
The algorithm set_symmetric_difference() constructs a sorted symmetric difference of the elements from the two ranges. This means that the constructed range includes copies of the elements that are present in the range [start1, finish1) (but not present in the range [start2, finish2)) and copies of the elements that are present in the range [start2, finish2) (but not in the range [start1, finish1)). It returns the end of the constructed range.
For example, suppose we have two sets:
1 2 3 4 5
and
3 4 5 6 7
The set_symmetric_difference() of these two sets is:
1 2 6 7
The result of set_symmetric_difference() is undefined if the result range overlaps with either of the original ranges.
set_symmetric_difference() assumes that the ranges are sorted using operator<(), unless an alternative comparison function object (comp) is provided.
Use the set_symmetric_difference() algorithm to obtain a result that includes elements that are present in the first set and not in the second.
At most ((finish1 - start1) + (finish2 - start2)) * 2 -1 comparisons are performed.
// // set_s_di.cpp // #include <algorithm> #include <set> #include <iostream> int main () { #ifndef _RWSTD_NO_NAMESPACE using namespace std; #endif // Initialize some sets. int a1[] = {1,3,5,7,9,11}; int a3[] = {3,5,7,8}; set<int, less<int>,allocator<int> > odd(a1+0, a1+6), result, smalll(a3+0, a3+4); // Create an insert_iterator for result. insert_iterator<set<int, less<int>,allocator<int> > > res_ins(result, result.begin()); // Demonstrate set_symmetric_difference. cout << "The symmetric difference of:" << endl << "{"; copy(smalll.begin(),smalll.end(), ostream_iterator<int,char,char_traits<char> > (cout," ")); cout << "} with {"; copy(odd.begin(),odd.end(), ostream_iterator<int,char,char_traits<char> > (cout," ")); cout << "} =" << endl << "{"; set_symmetric_difference(smalll.begin(), smalll.end(), odd.begin(), odd.end(), res_ins); copy(result.begin(),result.end(), ostream_iterator<int,char,char_traits<char> > (cout," ")); cout << "}" << endl << endl; return 0; } Program Output:
The symmetric difference of: {3 5 7 8 } with {1 3 5 7 9 11 } = {1 8 9 11 }
includes(), Iterators, set_union(), set_intersection(), set_difference()
ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 25.3.5.5