C++計算排名

在C++中,你可以使用標準庫中的算法來對數組進行排序,然後根據排序後的結果計算排名。以下是一個簡單的例子,展示了如何對數組進行排序,並計算每個數字的排名:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {12, 18, 2, 9, 20};

    // 對數組進行排序
    std::sort(numbers.begin(), numbers.end());

    // 計算每個數字的排名
    for (int i = 0; i < numbers.size(); ++i) {
        std::cout << numbers[i] << " 的排名是 " << i + 1 << std::endl;
    }

    return 0;
}

這個程式首先定義了一個vector來存放要排序的數字。然後使用std::sort算法對數組進行升序排序。排序後,我們遍歷數組,並輸出每個數字的排名。

請注意,排名從1開始,而不是從0開始。這是一個常見的慣例,因為排名通常被視為一個序列號,從第一個開始計數。

如果你想要一個數字在數組中出現多次時,每個出現的數字都有一個排名,那麼你可以使用一個累加器來追蹤已經輸出的排名,並在輸出排名時增加累加器。以下是一個修改後的例子:

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

int main() {
    std::vector<int> numbers = {12, 18, 2, 9, 20, 9, 2, 20};

    // 對數組進行排序
    std::sort(numbers.begin(), numbers.end());

    // 使用std::map來追蹤每個數字出現的次數
    std::map<int, int> count_map;
    for (const auto& num : numbers) {
        ++count_map[num];
    }

    // 計算每個數字的排名
    int rank = 1;
    for (const auto& num_count : count_map) {
        for (int i = 0; i < num_count.second; ++i) {
            std::cout << num_count.first << " 的排名是 " << rank << std::endl;
            ++rank;
        }
    }

    return 0;
}

這個程式使用了一個std::map來追蹤每個數字在數組中出現的次數。然後,我們遍歷這個map,對於每個數字,我們輸出它的排名,直到我們輸出了它出現的次數。這樣,每個數字都會有一個排名,即使它在數組中出現了多次。