In C++, sets are associative containers that store unique elements. On the other hand, pairs allow the users to store two data of different or the same type into a single object. In this article, we will learn how we can create a set of pairs in C++.
Example
Input: p1={1, 2} p2 ={3, 4} Output: Elements of set: Pair 1: (1, 2) Pair 2: (3, 4)
Create a Set of Pairs in C++
To create a set of pairs in C++, we can simply use the following syntax:
set<pair<dataType, dataType>>This will declare a set where each element is a pair. We can then insert the pairs into the set using the std::set::insert() method.
C++ Program to Create a Set of Pairs
// C++ program to create a set of pairs using pair
#include <iostream>
#include <set>
#include <utility>
using namespace std;
// Driver Code
int main()
{
// Initialize a set of set of pairs
set<pair<int, int> > s;
// Insert pairs into the set
s.insert({ 10, 20 });
s.insert({ 30, 40 });
s.insert({ 50, 60 });
s.insert({ 70, 80 });
// Duplicate pair, won't be inserted as set stores
// unique elements only
s.insert({ 30, 40 });
int i = 1;
// Print the pairs present in the set
cout << "Elements of Set:" << endl;
for (auto pair : s) {
cout << "Pair " << i++ << ": ";
cout << "(" << pair.first << ", " << pair.second
<< ")" << endl;
}
return 0;
}
Output
Elements of Set: Pair 1: (10, 20) Pair 2: (30, 40) Pair 3: (50, 60) Pair 4: (70, 80)
Time Complexity: O(N) where N is the number of pairs in the set.
Auxiliary Space: O(N)