Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Medium
  • Last Updated : 06 Mar, 2019

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:




// 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;
}
Output:
Element    index
1    4
2    0
3    2
5    1
7    3

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :