Map of Sets in C++ STL with Examples
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 numbers corresponding to a number
or
map<set<datatype>, datatype> map_of_set : stores a number corresponding to a set of numbers
Lets see how to implement Maps of Sets in C++:
C++
// C++ program to demonstrate use of map of set #include <bits/stdc++.h> using namespace std; void show(map< int , set<string> >& mapOfSet) { // Using iterator to access // key, value pairs present // inside the mapOfSet for ( auto it = mapOfSet.begin(); it != mapOfSet.end(); it++) { // Key is integer cout << it->first << " => " ; // Value is a set of string set<string> st = it->second; // Strings will be printed // in sorted order as set // maintains the order for ( auto it = st.begin(); it != st.end(); it++) { cout << (*it) << ' ' ; } cout << '\n' ; } } // Driver code int main() { // Declaring a map whose key // is of integer type and // value is a set of string map< int , set<string> > mapOfSet; // Inserting values in the // set mapped with key 1 mapOfSet[1].insert( "Geeks" ); mapOfSet[1].insert( "For" ); // Set stores unique or // distinct elements only mapOfSet[1].insert( "Geeks" ); // Inserting values in the // set mapped with key 2 mapOfSet[2].insert( "Is" ); mapOfSet[2].insert( "The" ); // Inserting values in the // set mapped with key 3 mapOfSet[3].insert( "Great" ); mapOfSet[3].insert( "Learning" ); // Inserting values in the // set mapped with key 4 mapOfSet[4].insert( "Platform" ); show(mapOfSet); return 0; } |
1 => For Geeks 2 => Is The 3 => Great Learning 4 => Platform
Please Login to comment...