Sorting an array according to another array using pair in STL in C++

C++Server Side ProgrammingProgramming

Suppose we have two different arrays. We have to sort one array based on the other array using C++ STL pair class. Consider two arrays are like A1 = [2, 1, 5, 4, 9, 3, 6, 7, 10, 8], and another array is like A2 = [A, B, C, D, E, F, G, H, I, J], The output will be like: A1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], A2 = [B, A, F, D, C, G, H, J, E, I]

Here we are using the pairs of C++ STL. The pair is formed by taking one element from A1, another element from A2. Then simply use the sorting function. One thing we have taken under consideration, that the first element in the pair, should form the array, according to which the sorting is performed.

Example

 Live Demo

#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
template <class T>
void display(T arr[], int n) {
   for (int i = 0; i < n; i++)
   cout << arr[i] << " ";
}
void sortUsingSecondArr(int A1[], char A2[], int n){
   pair<int, char> pair_arr[n];
   for (int i = 0; i < n; i++) {
      pair_arr[i].first = A1[i];
      pair_arr[i].second = A2[i];
   }
   sort(pair_arr, pair_arr + n);
   for (int i = 0; i < n; i++) {
      A1[i] = pair_arr[i].first;
      A2[i] = pair_arr[i].second;
   }
}
int main() {
   int n = 10;
   int A1[] = {2, 1, 5, 4, 9, 3, 6, 7, 10, 8};
   char A2[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
   cout << "Before Sorting: "<<endl;
   cout << "First Array : "; display(A1, n);
   cout << "\nSecond Array: "; display(A2, n);
   sortUsingSecondArr(A1, A2, n);
   cout << "\n\nAfter Sorting: "<<endl;
   cout << "First Array : "; display(A1, n);
   cout << "\nSecond Array: "; display(A2, n);
}

Output

Before Sorting:
First Array : 2 1 5 4 9 3 6 7 10 8
Second Array: A B C D E F G H I J
After Sorting:
First Array : 1 2 3 4 5 6 7 8 9 10
Second Array: B A F D C G H J E I
raja
Published on 21-Oct-2019 12:19:00
Advertisements