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 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
#include <iostream>
#include <vector>
#include <algorithm>
usingnamespace 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.