Difference between revisions of "CPP/STL/SetDifference"

From ProgrammingExamples
< CPP
Jump to: navigation, search
(Created page with '==SetDifference.cpp== <source lang="cpp"> #include <iostream> #include <list> #include <algorithm> #include <string> #include <iterator> template<class Coll> void print(const Co…')
 
(SetDifference.cpp)
Line 7: Line 7:
 
#include <iterator>
 
#include <iterator>
  
 +
//prints a any collection that supports begin and end iterator
 
template<class Coll>
 
template<class Coll>
void print(const Coll c)
+
void print(const Coll c){
{
+
 
   using std::cout;
 
   using std::cout;
 
   using std::endl;
 
   using std::endl;
Line 25: Line 25:
 
{
 
{
 
   using namespace std;
 
   using namespace std;
   string s1 = "abc";
+
   string s1 = "abce";
   string s2 = "abd";
+
   string s2 = "abde";
 
   list<char> a = list<char>(s1.begin(),s1.end());
 
   list<char> a = list<char>(s1.begin(),s1.end());
 
   list<char> b = list<char>(s2.begin(),s2.end());
 
   list<char> b = list<char>(s2.begin(),s2.end());
 
   list<char> res;
 
   list<char> res;
 +
 +
  //need to sort before call to set_difference
 +
  b.size(); a.sort();
  
 
   std::set_difference(a.begin(),a.end(),b.begin(),b.end(),std::back_insert_iterator<list<char> >(res));
 
   std::set_difference(a.begin(),a.end(),b.begin(),b.end(),std::back_insert_iterator<list<char> >(res));
 +
 
   print(a);
 
   print(a);
 
   cout << " - ";
 
   cout << " - ";

Revision as of 00:56, 29 June 2010

SetDifference.cpp

#include <iostream>
#include <list>
#include <algorithm>
#include <string>
#include <iterator>
 
//prints a any collection that supports begin and end iterator
template<class Coll>
void print(const Coll c){
  using std::cout;
  using std::endl;
 
  typename Coll::const_iterator itr = c.begin();
  cout << "{ ";
  while(itr != c.end())
  {
    cout << *itr++ << " ";
  }
  cout << "}";
}
 
int main()
{	
  using namespace std;
  string s1 = "abce";
  string s2 = "abde";
  list<char> a = list<char>(s1.begin(),s1.end());
  list<char> b = list<char>(s2.begin(),s2.end());
  list<char> res;
 
  //need to sort before call to set_difference
  b.size(); a.sort();
 
  std::set_difference(a.begin(),a.end(),b.begin(),b.end(),std::back_insert_iterator<list<char> >(res));
 
  print(a);
  cout << " - ";
  print(b);	
  cout << " = ";
  print(res);
  cout << endl;
 
  return 0;
}