Search code examples
c++armadillo

C++ Armadillo: Get the ranks of the elements in a vector


Suppose I have a vector, and I want to get the ranks of the elements if they were sorted.

So if I have the vector:

0.5
1.5
3.5
0.1

and I need returned the ranks of each element:

2
3
4
1

Is there a way to do this in Armadillo? This is different than the previous post since we are getting the ranks and not the indices before sorting.


Solution

  • Here, check this out:

    #include<iostream>
    #include<vector> // std:: vector
    #include <algorithm> // std::sort
    #include <map> // std::map
    
    using namespace std;
    
    
    int main() {
        vector<double> myVector = { 0.5, 1.5, 3.5, 0.1 };
        vector<double> Sorted = myVector;
    
        std::sort(Sorted.begin(), Sorted.end());
    
        map<double, int> myMap;
    
        for (int i = 0; i < Sorted.size() ; i++)
        {
            myMap.insert(make_pair(Sorted[i],i));
        }
    
        for (int i = 0; i < myVector.size() ; i++)
        {
            auto it = myMap.find(myVector[i]);
            cout << it->second + 1 << endl;
        }
    
        return 0;
    };
    

    Output:

    enter image description here