How to Access Elements of Set of Maps in C++?
Last Updated :
02 Feb, 2024
In C++, a set of maps can be used to store multiple maps of key-value pairs sorted according to their number and values of elements such as graphs. In this article, we will explore how we can access the elements of a set of maps in C++.
Example:
Input: { { {1: "C++"}, {2:" Python"} },
{ {3:" Java"}, {4: "Rust"} }
}
Output:
Value Associated with Key 3: Rust
Access Elements of Set of Maps in C++
The Set of Map is a multidimensional container, so there will be multilevel access in the set of maps. Assume that you want to access the element with key ‘k’:
- We will first use the range-based for loop to iterate through the parent set.
- Now, inside the first loop, each element will be a map container. So, we will find the value of ‘k’ using the std:map::at() function.
C++ Program to Access Elements of Set of Pairs
C++
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main()
{
set<map< int , char > > setOfMaps;
map< int , char > map1{ { 1, 'a' },
{ 3, 'b' },
{ 5, 'c' } };
map< int , char > map2{ { 1, 'f' },
{ 3, 'e' },
{ 5, 'd' } };
setOfMaps.insert(map1);
setOfMaps.insert(map2);
int key = 3;
for ( const auto & map : setOfMaps) {
if (map.count(key) > 0) {
char value = map.at(key);
cout << "Value associated with key " << key
<< " is " << value << endl;
}
}
return 0;
}
|
Output
Value associated with key 3 is b
Value associated with key 3 is e
Time Complexity: O(N x M) where N is the size of the Set and M is the size of Maps present inside the set.
Auxilary Space: O(1)
Share your thoughts in the comments
Please Login to comment...