How to use the set_intersection() function in C++

In this shot, we will learn how to use the set_intersection() function in C++.

The set_intersection() function is available in the <algorithm> library in C++.

The set_intersection() function is used to find the intersection of the two sorted ranges, which is formed only by the common elements between the sets.

Syntax

The syntax of the set_intersection() function is shown below:

OutputIterator set_intersection(first1, last1, first2, last2, res)

Parameters

The set_intersection() method takes the following parameters:

  • First1: The input iterator to the initial position of the first sorted sequence.
  • Last1: The input iterator to the final position of the first sorted sequence.
  • First2: The input iterator to the initial position of the second sorted sequence.
  • Last2: The input iterator to the final position of the second sorted sequence.
  • Res: The output iterator to the initial position of the range where the resulting sequence is stored.

Returns

The set_intersection() returns an iterator to the end of the constructed range.

Code

Let’s have a look at the code now.

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int first[] = { 25, 110, 105, 120, 125 };
int second[] = { 150, 120, 105, 225, 25 };
int n = sizeof(first) / sizeof(first[0]);
cout << "First array contains :";
for (int i = 0; i < n; i++)
cout << " " << first[i];
cout << "\n";
cout << "Second array contains :";
for (int i = 0; i < n; i++)
cout << " " << second[i];
cout << "\n\n";
vector<int> vec(10);
vector<int>::iterator it1, st1;
sort(first, first + n);
sort(second, second + n);
it1 = set_intersection(first, first + n, second, second + n, vec.begin());
cout << "The intersection has " << (it1 - vec.begin())<< " elements:\n";
for (st1 = vec.begin(); st1 != it1; ++st1)
cout << ' ' << *st1;
cout << '\n';
return 0;
}

Explanation:

  • In lines 1 to 3, we imported the required header files.

  • In line 6, we made a main() function.

  • In line 9 and 10, we initialized two arrays.

  • From lines 13 to 15, we displayed the elements of the first array.

  • From lines 18 to 20, we displayed the elements of the second array.

  • In line 23, we declared a vector of int type.

  • In line 24, we declared two iterators to a vector of int type.

  • In lines 26 and 27, we sorted the two arrays.

  • In line 29, we used the set_intersection() function to obtain the intersection and store the output vector’s initial position in the iterator.

  • In line 31, we displayed the number of elements in the intersection.

  • In lines 32 and 33, we displayed the elements of intersection using the iterator and loop.

So, this is how to use the set_intersection() function in C++.

Free Resources