
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_Union in STL
The Set Union is an operation used to find all elements that are present in either of the sets or in both. In this article, we will learn how to use the set_union algorithm from the Standard Template Library (STL) in C++ to find the union of two sets.
What is Set Union?
The set union is an arithmetic operation performed between two sets to find all elements that are present in either of the sets or in both. In C++, we have set_union which is a built-in algorithm provided by C++ STL that computes the union of two sorted ranges of sets. That is, it returns all unique elements that are present in at least one of the 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} Union A ? B = {1, 2, 3, 4, 6}
Using set_union Function in STL
The set_union function is defined in the <algorithm> header of STL. Below are some points about this algorithm:
- Header: <algorithm>
-
Syntax:
set_union(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_union in C++ STL
Following are steps/algorithm to use set_union using C++ STL:
- Include the <algorithm> and <vector> header files.
- Define and initialize two sorted vectors (or sets).
- Use set_union() to find all unique elements from both ranges.
- Store the result in another vector or print directly using output iterator.
C++ Program to Implement set_union 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 union A ? B set_union(A.begin(), A.end(), B.begin(), B.end(), back_inserter(result)); cout << "Union of A and B: "; for (int x : result) { cout << x << " "; } cout << endl; return 0; }
The output of above code will be
Union of A and B: 1 2 3 4 6
Time and Space Complexity
- set_union: 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.