# 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}

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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 ``using` `namespace` `std;`` ` `void` `sortArr(``int` `arr[], ``int` `n)``{`` ` `    ``// Vector to store element``    ``// with respective present index``    ``vector > 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);``    ``sortArr(arr, n);`` ` `    ``return` `0;``}`

Output:

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

My Personal Notes arrow_drop_up