Sort an array of strings based on the given order | C ++ program to sort an array of strings based on the given order ; For storing priority of each character ; Custom comparator function for sort ; Loop through the minimum size between two words ; Check if the characters at position i are different , then the word containing lower valued character is smaller ; When loop breaks without returning , it means the prefix of both words were same till the execution of the loop . Now , the word with the smaller size will occur before in sorted order ; Function to print the new sorted array of strings ; Mapping each character to its occurrence position ; Sorting with custom sort function ; Printing the sorted order of words ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_map < char , int > mp ; bool comp ( string & a , string & b ) { for ( int i = 0 ; i < min ( a . size ( ) , b . size ( ) ) ; i ++ ) { if ( mp [ a [ i ] ] != mp [ b [ i ] ] ) return mp [ a [ i ] ] < mp [ b [ i ] ] ; } return ( a . size ( ) < b . size ( ) ) ; } void printSorted ( vector < string > words , string order ) { for ( int i = 0 ; i < order . size ( ) ; i ++ ) mp [ order [ i ] ] = i ; sort ( words . begin ( ) , words . end ( ) , comp ) ; for ( auto x : words ) cout << x << " ▁ " ; } int main ( ) { vector < string > words = { " word " , " world " , " row " } ; string order = { " worldabcefghijkmnpqstuvxyz " } ; printSorted ( words , order ) ; return 0 ; }