
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Implement Set_Intersection in STL
The Set Intersection is an operation used to find all elements that are common in both sets. In this article, we will learn how to use the set_intersection algorithm from the Standard Template Library (STL) in C++ to find the intersection of two sets.
What is Set Intersection?
The set intersection is an arithmetic operation performed between two sets to find all elements that are common in both sets. In C++, we have set_intersection which is a built-in algorithm provided by C++ STL that computes the intersection of two sorted ranges of sets. That is, it returns the elements that are present in both ranges. The input ranges must be sorted in ascending order.
For example, consider the following sets:
Set A = {1, 2, 3, 4} Set B = {2, 4, 6} Intersection A ? B = {2, 4}
Using set_intersection Function in STL
The set_intersection function is defined in the <algorithm> header of STL. Below are some points about this algorithm:
- Header: <algorithm>
-
Syntax:
set_intersection(start1, end1, start2, end2, result_iterator);
- Parameters:
- start1, end1: Start and end iterators of the first sorted range.
- start2, end2: Start and end iterators of the second sorted range.
- result_iterator: Iterator to the beginning of the destination range.
Steps to Implement set_intersection in C++ STL
Following are steps/algorithm to use set_intersection using C++ STL:
- Include the <algorithm> and <vector> header files.
- Define and initialize two sorted vectors (or sets).
- Use set_intersection() to find elements that are common in both ranges.
- Store the result in another vector or print directly using output iterator.
C++ Program to Implement set_intersection using STL
The below code is the implementation of the above algorithm in C++ language.
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> A = {1, 2, 3, 4}; vector<int> B = {2, 4, 6}; vector<int> result; // Compute set intersection A ? B set_intersection(A.begin(), A.end(), B.begin(), B.end(), back_inserter(result)); cout << "Elements common in both A and B: "; for (int x : result) { cout << x << " "; } cout << endl; return 0; }
The output of above code will be:
Elements common in both A and B: 2 4
Time and Space Complexity
- set_intersection: O(n), where n is the sum of the sizes of both input ranges.
Space Complexity: O(n), where n is the size of the result range.