function returns the ordered array index

Hello everyone, can anyone tell me is there a special function which returns the index of sorted array in c++. basically, I have an array like
V=[-8.0 ,-1.0, 0.0, -7.0, 0.0, 0.0, -13.0] The function will sort them from the most negative will return me the index of the ordered negative values. Like 7, 1, 4 ,2,3,5,6 in our case.

Thank you so much
Hello computergeek01,

Thank you for your answer , I know sort function sorts the values , however what I need is their index (before they are sorted) . I need to get vector [7 1 4 2 3 5 6] as a result
Thank you so much
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


template<typename T> vector<int> indexOfSort( const vector<T> &V )
{
   struct PR
   {
      T value;
      int index;
   };

   int N = V.size();
   vector<PR> pr( N );
   for ( int i = 0; i < N; i++ ) pr[i] = { V[i], i };

   sort( pr.begin(), pr.end(), []( PR a, PR b ){ return a.value < b.value; } );

   vector<int> I( N );
   for ( int i = 0; i < N; i++ ) I[i] = pr[i].index;
   return I;
}


int main()
{
   vector<double> V = { -8.0 ,-1.0, 0.0, -7.0, 0.0, 0.0, -13.0 };
   vector<int> I = indexOfSort( V );
   for ( int e : I ) cout << e << ' ';
}


6 0 3 1 2 4 5 

Note that the indices start from 0. You can add 1 to all of them if that is your intention.
Last edited on
Thank you @lastchance
Topic archived. No new replies allowed.