Keep track of previous indexes after sorting a vector in C++ STL

Prerequisite: vector, vector pair sorting

Given a vector, keep track of the present indexes corresponding to each element and after sorting print element with its previous respective indexes.

Examples:



Input: Arr[] = {2, 5, 3, 7, 1}
Output: {1, 4} {2, 0} {3, 2} {5, 1} {7, 3}
Explanation:
Before sorting [index(element)]: [0(2), 1(5), 2(3), 3(7), 4(1)]
After sorting [previous_index(element)]: [4(1), 0(2), 2(3), 1(5), 3(7)]

Input: Arr[] = {4, 5, 10, 8, 3, 11}
Output: {3, 4} {4, 0} {5, 1} {8, 3} {10, 2} {11, 5}

Approach: The idea is to store each element with its present index in a vector pair and then sort all the elements of the vector, Finally, print the elements with its index associated with it.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to keep track
// of previous indexes
// after sorting a vector
  
#include <bits/stdc++.h>
using namespace std;
  
void sortArr(int arr[], int n)
{
  
    // Vector to store element
    // with respective present index
    vector<pair<int, int> > vp;
  
    // Inserting element in pair vector
    // to keep track of previous indexes
    for (int i = 0; i < n; ++i) {
        vp.push_back(make_pair(arr[i], i));
    }
  
    // Sorting pair vector
    sort(vp.begin(), vp.end());
  
    // Displaying sorted element
    // with previous indexes
    // corresponding to each element
    cout << "Element\t"
         << "index" << endl;
    for (int i = 0; i < vp.size(); i++) {
        cout << vp[i].first << "\t"
             << vp[i].second << endl;
    }
}
  
// Driver code
int main()
{
    int arr[] = { 2, 5, 3, 7, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    sortArr(arr, n);
  
    return 0;
}

chevron_right


Output:

Element    index
1    4
2    0
3    2
5    1
7    3


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.