How to Create a Set of Pairs in C++?
Last Updated :
27 Feb, 2024
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++
#include <iostream>
#include <set>
#include <utility>
using namespace std;
int main()
{
set<pair< int , int > > s;
s.insert({ 10, 20 });
s.insert({ 30, 40 });
s.insert({ 50, 60 });
s.insert({ 70, 80 });
s.insert({ 30, 40 });
int i = 1;
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)
Share your thoughts in the comments
Please Login to comment...