Open In App

How to Iterate Over a Set of Pairs in C++?

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to Declare, Insert, and Iterate through a Set
// of Pairs
  
#include <iostream>
#include <set>
#include <utility>
using namespace std;
  
int main()
{
    // Declare a set of pairs
    set<pair<int, string> > s;
  
    // Insert the pairs into the set
    s.insert({ 100, "Geek" });
    s.insert({ 200, "for" });
    s.insert({ 300, "Geeks" });
  
    // Iterate over the set of pairs through a range-based
    // for loop
    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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads