How to rank elements of a vector in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

using std::vector;

/*
    FUNCTION: getRanks
    -------------------
    Computes competition-style ranks for a vector of numbers.

    Ranking rules (Competition Ranking):
    ------------------------------------
    - Highest value gets rank 1
    - Equal values share the same rank
    - Next rank increases by the number of equal values

    Example:
        Values: 88, 4, 19, 4, 1, 31, 14, 1, 93, 17
        Ranks:   2, 7,  4, 7, 9,  3,  6, 9,  1,  5

    Implementation steps:
    ---------------------
    1. Make a sorted copy of the vector (descending)
    2. Assign ranks to each unique value
    3. Build a rank vector matching the original order
*/
vector<int> getRanks(const vector<int>& vec) {
    // Step 1: Create a sorted copy (descending)
    vector<int> sorted = vec;
    std::sort(sorted.begin(), sorted.end(), std::greater<int>());

    // Step 2: Map each unique value to its rank
    std::map<int, int> rankMap;   // value → rank
    int rank = 1;

    for (int value : sorted) {
        // Assign rank only once per unique value
        if (rankMap.find(value) == rankMap.end()) {
            rankMap[value] = rank;
        }
        rank++; // next rank position
    }

    // Step 3: Build ranking vector in original order
    vector<int> result;
    result.reserve(vec.size());

    for (int value : vec) {
        result.push_back(rankMap[value]);
    }

    return result;
}

/*
    FUNCTION: printRanking
    -----------------------
    Prints the original vector and its ranking.
*/
void printRanking(const vector<int>& vec, const vector<int>& ranks) {
    std::cout << "Original vec: [ ";
    for (int v : vec) std::cout << v << " ";
    std::cout << "]\n";

    std::cout << "Ranking vec : [ ";
    for (int r : ranks) std::cout << r << " ";
    std::cout << "]\n";
}

int main() {
    vector<int> vec = {88, 4, 19, 4, 1, 31, 14, 1, 93, 17};

    // Compute ranks
    vector<int> rankingVec = getRanks(vec);

    printRanking(vec, rankingVec);
}


/*
run:

Original vec: [ 88 4 19 4 1 31 14 1 93 17 ]
Ranking vec : [ 2 7 4 7 9 3 6 9 1 5 ]

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz
...