Sort the array of strings according to alphabetical order defined by another string in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of strings, and another string is there for the reference. We have to take the reference string and using the order of the characters in the reference string we will sort the string array. Here we are considering the strings in the array, and the reference string is in lower case letters.

Suppose the string array is like: [“hello”, “programming”, “science”, “computer”, “india”], the reference string is like: “pigvxbskyhqzelutoacfjrndmw”, After sorting the output string will be like [“programming”, “india”, “science”, “hello”, “computer”]

The task is simple. We have to traverse the reference string, then store the character into the map as key, and the index as value. Now to sort the string, we have to compare the strings based on that map, not the ASCII character ordering. Compare the values mapped to those particular characters in the map, if the character c1 appears before c2, then c1 < c2.


 Live Demo

#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
unordered_map<char, int> char_map;
bool compare(string c1, string c2) {
   for (int i = 0; i < min(c1.size(), c2.size()); i++) {
      if (char_map[c1[i]] == char_map[c2[i]])
      return char_map[c1[i]] < char_map[c2[i]];
   return c1.size() < c2.size();
int main() {
   string str = "pigvxbskyhqzelutoacfjrndmw";
   vector<string> v{ "hello", "programming", "science", "computer", "india" };
   for (int i = 0; i < str.size(); i++)
   char_map[str[i]] = i;
   sort(v.begin(), v.end(), compare);
   // Print the strings after sorting
   for (auto x : v)
   cout << x << " ";


programming india science hello computer
Published on 21-Oct-2019 12:17:06