Map of Sets in C++ STL with Examples
Last Updated :
18 Feb, 2023
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element.
Map of Sets in STL: A map of sets can be very useful in designing complex data structures and algorithms.
Syntax:
map<datatype, set<datatype>> map_of_set : stores a set of datatypes corresponding to a datatype
or
map<set<datatype>, datatype> map_of_set : stores a datatype corresponding to a set of datatypes
Let’s see how to implement Maps of Sets in C++:
C++
#include <bits/stdc++.h>
using namespace std;
void show(map< int , set<string> >& mapOfSet)
{
for ( auto it = mapOfSet.begin();
it != mapOfSet.end();
it++) {
cout << it->first << " => " ;
set<string> st = it->second;
for ( auto it = st.begin();
it != st.end(); it++) {
cout << (*it) << ' ' ;
}
cout << '\n' ;
}
}
int main()
{
map< int , set<string> > mapOfSet;
mapOfSet[1].insert( "Geeks" );
mapOfSet[1].insert( "For" );
mapOfSet[1].insert( "Geeks" );
mapOfSet[2].insert( "Is" );
mapOfSet[2].insert( "The" );
mapOfSet[3].insert( "Great" );
mapOfSet[3].insert( "Learning" );
mapOfSet[4].insert( "Platform" );
show(mapOfSet);
return 0;
}
|
Output
1 => For Geeks
2 => Is The
3 => Great Learning
4 => Platform
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...