C++ Program to Sort a Dictionary By Values


There are some data structures called dictionaries that are available in various computer languages. A particular form of quicker data structure that stores data based on keys and values is a dictionary. It keeps the key-value pair there so that certain components can be quickly searched by the keys in virtually real-time. The dictionary-like data structure is contained in the C++ STL language standard. This data structure is known by the name "map." The map generates a pair of keys and values of any type (the type must be defined before compilation as we are using C++). In this section, we'll look at how to use C++ to sort dictionary entries according to their values.

Let's first look at how the map data structure is defined. Two kinds are required for these inside templates. The required libraries and syntax are displayed below −

Syntax to define Map Data Structure

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

To use the map data structure in this case, we must import the "map" library. This requires types 1 and 2 of data. Type1 denotes the key parameter's data type, whereas type2 denotes the value type. The object derived from the map type class is called a mapVariable. Let's now examine how to organize the map based on these crucial factors.

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.second < b.second;
}
 
//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 ) {
      cout << "Key: " << it.first << ", value: " << it.second << endl;
      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 },
        { "Four", 4 },
        { "One", 1 },
        { "Five", 5 }
   };
   
   cout << "Before Sorting: " << endl;
   display( givenMap );
  
   cout << "After Sorting: " << endl;
   givenMap = sorting( 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: One, value: 1
Key: Two, value: 2
Key: Three, value: 3
Key: Four, value: 4
Key: Five, value: 5

We have performed the sorting, If we store the final result in the map, we will not see any difference after and before sorting this is because the map data structure holds the data in the sorted form of their keys most of the time. Here we are using vectors to sort them based on values. If we print them directly from the vector the order can be found.

Using a Set of Pairs

The key-value pairs from a map data structure can be sorted using a set, another type of data structure. Data are kept in sorted order in the set data structure. As a result, after adding elements to the collection, sorting is not necessary again. For a better understanding, let's have a look at the algorithm.

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 a 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 ) {
      cout << "Key: " << it.first << ", value: " << it.second << endl;
      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 },
        { "Four", 4 },
        { "One", 1 },
        { "Five", 5 }
   };
   
   cout << "Before Sorting: " << endl;
   display( givenMap );
  
   cout << "After Sorting: " << endl;
   givenMap = sorting( 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: One, value: 1
Key: Two, value: 2
Key: Three, value: 3
Key: Four, value: 4
Key: Five, value: 5

Conclusion

In this post, we've seen two distinct methods for sorting the dictionary data structure (referred to as a map in C++) and sorting them by values. Since the maps are hash maps, the data for their keys are stored using hashing algorithms. Although the keys are distinct, the values for separate keys could be the same. Using set and vector sorting, where the vectors and sets carry pairings, we have sorted them. There are two different sorts for every pair. A value type is the second type, whereas a key type is the first.

Updated on: 13-Dec-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements