C++ Program to Sort Dictionary by keys


In different programming languages, there are some data structures available that are known as dictionaries. The dictionaries are a special kind of faster data structure that stores data based on keys and values. It stores the key-value pair into it so that some elements can easily be searched in almost constant time by the keys. In C++, the dictionary−like data structure is present in C++ STL. The name of this data structure is named as ‘map’. The map creates a pair of keys and values of any type (since we are using C++, the type must be defined before compilation). In this section, we will see how we can sort the entries of the dictionary based on their key parameters in C++.

Let us see how to define map data structure first. This will take two types of templates. The syntax and required library are shown below −

Syntax to define Map Data Structure

#include <map>
map<type1, type2> mapVariable;

Here, we need to import the ‘map’ library to use the map data structure. This takes two data types type1 and type2. Type1 refers to the data type for the key parameter whereas type2 is for the value type. The mapVariable is the object created from the map type class. Now let us see how to sort the map using their key parameters.

Using Vector of Pairs

In this idea, we just create a vector (dynamic array, which is coming as another element from C++ STL) of key-value pairs. Then perform sorting by creating your comparing function. Then store the contents again into a map in a sorted format.

Algorithm

  • Take map M as input

  • Define a dynamic array A to store key-value pairs

  • For each key-value pair p in M, do

    • insert p into A

  • End for

  • sort A based on their keys

  • create empty map newMap

  • For each pair p in A −

    • insert pair p into newMap

  • End for

  • return newMap

Example

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

// Create a comparator function to perform key-value pair comparison
bool compare ( pair <string, int> &a, pair <string, int> &b ){
   return a.first < b.first;
}
 
//Define sorting function to sort given dictionary or map
map <string, int> sorting( map <string, int> givenMap ){
   vector<pair <string, int> > pairVec;
   map<string, int> newMap;
   
   for ( auto& it : givenMap ) {
      pairVec.push_back( it );
   }
   
   sort( pairVec.begin(), pairVec.end(), compare);
   
   for ( auto& it : pairVec ) {
      newMap.insert( { it.first, it.second } );
   }
   return newMap;
}

void display( map <string, int>& givenMap ){
   for ( auto& it : givenMap ) {
      cout << "Key: " << it.first << ", value: " << it.second << endl;
   }
}
   
int main(){ 
   map<string, int> givenMap;
   
   givenMap = { { "Three", 3 },
        { "Two", 2 },
        { "One", 1 } 
   };
   
   cout << "Before Sorting: " << endl;
   display( givenMap );
  
   cout << "After Sorting: " << endl;
   givenMap = sorting( givenMap );
   display( givenMap ); 
}

Output

Before Sorting: 
Key: One, value: 1
Key: Three, value: 3
Key: Two, value: 2
After Sorting: 
Key: One, value: 1
Key: Three, value: 3
Key: Two, value: 2

We have performed the sorting, but we cannot see any difference here. This is because the map data structure itself holds the key-value pairs based on the sorted form of their keys, but it is not always the case. In a few scenarios, it can store data out of their order.

Using a Set of Pairs

Set is another data structure that can be used to sort the key-value pairs from a map data structure. The set data structure stores data in sorted order. So it does not require an additional sorting step after inserting elements into the collection. Let us see the algorithm for a clear understanding.

Algorithm

  • Take map M as input

  • Define a set S to store key-value pairs

  • For each key-value pair p in M, do

    • insert p into S

  • End for

  • create empty map newMap

  • For each pair p in S −

    • insert pair p into newMap

  • End for

  • return newMap

Example

#include <iostream>
#include <set>
#include <map>
#include <algorithm>
using namespace std;

// Create comparator function to perform key-value pair comparison
struct compare {
   template <typename T>
   
   bool operator()(const T& a, const T& b) const
   {
      if (a.second != b.second) {
         return a.second < b.second;
      }
      return a.first < b.first;
   }
};
 
//Define sorting function to sort given dictionary or map
map <string, int> sorting( map <string, int> givenMap ){
   set<pair <string, int>, compare> pairSet( givenMap.begin(), givenMap.end() );
   map<string, int> newMap;
   
   for ( auto& it : givenMap ) {
      pairSet.insert( it );
   }
   
   for ( auto& it : pairSet ) {
      newMap.insert( { it.first, it.second } );
   }
   return newMap;
}

void display( map <string, int>& givenMap ){
   for ( auto& it : givenMap ) {
      cout << "Key: " << it.first << ", value: " << it.second << endl;
   }
}
   
int main(){ 
   map<string, int> givenMap;
   
   givenMap = { { "Three", 3 },
        { "Two", 2 },
        { "One", 1 },
        {"Four", 4},
        {"Five", 5},
   };
   
   cout << "Before Sorting: " << endl;
   display( givenMap );
  
   cout << "After Sorting: " << endl;
   givenMap = sorting( givenMap );
   display( givenMap ); 
}

Output

Before Sorting: 
Key: Five, value: 5
Key: Four, value: 4
Key: One, value: 1
Key: Three, value: 3
Key: Two, value: 2
After Sorting: 
Key: Five, value: 5
Key: Four, value: 4
Key: One, value: 1
Key: Three, value: 3
Key: Two, value: 2

Conclusion

In this article, we have seen two different techniques to sort the dictionary data structure (map in C++) and sort them based on their key parameters. The maps are hash−maps and they use hashing techniques to store data for their keys. The keys are unique, and values may be the same for different keys. We have arranged them using set and vector sorting where the vectors and sets are holding pairs. Each pair has two types. The first type is a key type, and the second type is a value type.

Updated on: 13-Dec-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements