How to Iterate Over a Set of Pairs in C++?
Last Updated :
02 Feb, 2024
In C++, a set is a container that stores unique values in some specified order while pairs are data structures that store key-value pairs. In this article, we will look at how we can iterate through a set of pairs in C++.
For Example,
Input:
mySet = { {100: "Geek"}, {200:" for"}, {300:" Geeks"} }
Output:
Set Elements:
Key: 100, Value: Geek
Key: 200, Value: for
Key: 300, Value: Geeks
Iterate Over a Set of Pairs in C++
In C++, we can simply iterate through the set of pairs using a range-based for loop. After that, we can access the first and second members of the pairs using the dot (.) operator.
C++ Program to Iterator Over a Set of Pairs
C++
#include <iostream>
#include <set>
#include <utility>
using namespace std;
int main()
{
set<pair< int , string> > s;
s.insert({ 100, "Geek" });
s.insert({ 200, "for" });
s.insert({ 300, "Geeks" });
cout << "Set Elements:" << endl;
for ( auto pair : s) {
cout << "Key: " << pair.first
<< ", Value: " << pair.second << endl;
}
return 0;
}
|
Output
Set Elements:
Key: 100, Value: Geek
Key: 200, Value: for
Key: 300, Value: Geeks
Time Complexity: O(N) where N is the number of elements present in the set.
Auxilary Space : O(1)
We can also use iterators and reverse_iterators for forward and reverse iteration of the set of pairs respectively.
Share your thoughts in the comments
Please Login to comment...