Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) std::set_difference

 

std::set_difference is an STL algorithm to create the subset of two sets of which the elements are all present in the first and absent in the second set (stored in any type of container).

 

#include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <vector>

int main()
{
  //v contains all values from zero to ten
  std::vector<int> v;
  v.push_back(0);
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  v.push_back(5);
  v.push_back(6);
  v.push_back(7);
  v.push_back(8);
  v.push_back(9);

  //w contains all squares from 1 to an including 25
  std::vector<int> w;
  w.push_back( 1);
  w.push_back( 4);
  w.push_back( 9);
  w.push_back(16);
  w.push_back(25);

  //x is the difference of v and w:
  //that is, the elements in v, that are
  //not in w
  std::vector<int> x;

  std::set_difference(v.begin(),v.end(),w.begin(),w.end(),
    std::back_inserter(x));

  //so x contains all three squares between zero to ten
  assert(x.size() == 7);
  assert(x[0] == 0);
  assert(x[1] == 2);
  assert(x[2] == 3);
  assert(x[3] == 5);
  assert(x[4] == 6);
  assert(x[5] == 7);
  assert(x[6] == 8);

  //Show x on screen
  std::copy(x.begin(),x.end(),std::ostream_iterator<int>(std::cout," "));
  std::cout << '\n';
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict