Performing Set Operations on Sequences - C++ STL Algorithm

C++ examples for STL Algorithm:set_difference

Description

Performing Set Operations on Sequences

Demo Code

#include <iostream>
#include <algorithm>
#include <string>
#include <set>
#include <iterator>

using namespace std;
template<typename C>
void printContainer(const C& c, char delim = ',', ostream& out = cout) {
   printRange(c.begin(), c.end(), delim, out);
}

template<typename Fwd>
void printRange(Fwd first, Fwd last, char delim = ',', ostream& out = cout) {
   out << "{";
   while (first != last) {
      out << *first;//from   www. j ava  2s .  com
      if (++first != last)
         out << delim << ' ';
   }
   out << "}" << endl;
}

int main() {

   cout << "Enter some strings: ";
   istream_iterator<string> start(cin);
   istream_iterator<string> end;
   set<string> s1(start, end);

   cin.clear();

   cout << "Enter some more strings: ";
   set<string> s2(++start, end);

   set<string> setUnion;
   set<string> setInter;
   set<string> setDiff;

   set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(setUnion, setUnion.begin()));

   set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(setDiff, setDiff.begin()));


   set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(setInter, setInter.begin()));

   cout << "Union:\n";
   printContainer(setUnion);
   cout << "Difference:\n";
   printContainer(setDiff);
   cout << "Intersection:\n";
   printContainer(setInter);
}

Result


Related Tutorials