set_difference() in C++ STL

The C++ Standard Library consists of the header, <algorithm> which defines a collection of functions (principally designed to deal with a range of elements). set_difference() is a method in the STL that constructs the difference of two sorted ranges

Note:
The difference of two sets is formed by the elements that are present in the first set, but not in the second one.

Syntax:

set_difference( iterator_begin1, iterator_end1, iterator_begin2, iterator_end2, iterator_result, comparator); //comparator is optional

Parameters: The set_difference() method accepts 6 parameters

  • iterator_begin1, iterator_end1: Iterator to the initial and final position of first sorted sequence ( Note: the range is [iterator_begin1, iterator_end1) )
  • iterator_begin2, iterator_end2: Iterator to the initial and final position of second sorted sequence ( Note: the range is [iterator_begin2, iterator_end2) )
  • iterator_result: Iterator where resulting output is stored
  • comparator: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.

Return value: An iterator to the end of the constructed range.

Example of set_difference() method

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main () {

  vector<int> v1;
  v1.push_back(5);
  v1.push_back(6);
  v1.push_back(3);
  v1.push_back(1);
  v1.push_back(2);

  vector<int> v2;
  v2.push_back(4);
  v2.push_back(5);
  v2.push_back(1);
  v2.push_back(9);
  v2.push_back(2);

  vector<int> v(10);
  vector<int>::iterator it;

  sort (v1.begin(),v1.end());   // 1 2 3 5 6
  sort (v2.begin(),v2.end());   // 1 2 4 5 9

  it= set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), v.begin());

  v.resize(it-v.begin());

  cout<<"The difference is : \n";
  for (it=v.begin(); it!=v.end(); ++it)
    cout << *it <<"  ";
}

Output:

The difference is:
3  6

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top