Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Sorting an array according to another array using pair in STL

  • Difficulty Level : Easy
  • Last Updated : 24 Apr, 2018

We are given two arrays. We need to sort one array according to another.


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input : 2 1 5 4 9 3 6 7 10 8
        A B C D E F G H I J

Output : 1 2 3 4 5 6 7 8 9 10 
         B A F D C G H J E I 
Here we are sorting second array
(a character array) according to 
the first array (an integer array).

We have discussed different ways in below post.
Sort an array according to the order defined by another array

In this post we are focusing on using the pair container present in STL of C++.

To achieve our task we are going to make pairs of respective elements from both the arrays.Then simply use the sort function. The important thing to note is, the first element in the pairs should be from the array according to which the sorting is to be performed.

// Sort an array according to 
// other using pair in STL.
#include <bits/stdc++.h>
using namespace std;
// Function to sort character array b[]
// according to the order defined by a[]
void pairsort(int a[], char b[], int n)
    pair<int, char> pairt[n];
    // Storing the respective array
    // elements in pairs.
    for (int i = 0; i < n; i++) 
        pairt[i].first = a[i];
        pairt[i].second = b[i];
    // Sorting the pair array.
    sort(pairt, pairt + n);
    // Modifying original arrays
    for (int i = 0; i < n; i++) 
        a[i] = pairt[i].first;
        b[i] = pairt[i].second;
// Driver function
int main()
    int a[] = {2, 1, 5, 4, 9, 3, 6, 7, 10, 8};
    char b[] = {'A', 'B', 'C', 'D', 'E', 'F'
                         'G', 'H', 'I', 'J'};
    int n = sizeof(a) / sizeof(a[0]);
    // Function calling
    pairsort(a, b, n);
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
    cout << endl;
    for (int i = 0; i < n; i++)
        cout << b[i] << " ";
    return 0;


1 2 3 4 5 6 7 8 9 10 
B A F D C G H J E I 

This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!