最大元素的個數c++

要找到一個數組中最大元素的數量,可以使用一個簡單的循環來實現。下面是一個C++代碼示例:

#include <iostream>
#include <vector>

int findMaxElements(std::vector<int>& arr) {
    int count = 0;
    for (int i = 0; i < arr.size(); i++) {
        if (arr[i] > arr[count]) {
            count = i;
        }
    }
    return count + 1;
}

int main() {
    std::vector<int> arr = {3, 1, 4, 2, 5, 8, 6};
    std::cout << "The number of maximum elements is: " << findMaxElements(arr) << std::endl;
    return 0;
}

這段代碼定義了一個函式 findMaxElements,它接受一個整數向量作為參數,並返回最大元素的數量。該函式使用一個循環遍歷向量中的每個元素,並在必要時更新計數器。最後,它將計數器加一併返回,以確保正確計數所有最大元素的數量。

在主函式中,我們創建了一個示例向量並調用 findMaxElements 函式來獲取最大元素的數量。然後,我們將結果列印到控制台上。在這個例子中,輸出將是「The number of maximum elements is: 3」,因為向量中有三個最大元素(5、8和6)。