如何用c++求最大值

在C++中,你可以使用多種方法來求一組數值中的最大值。以下是幾種常見的方法:

  1. 使用內置的 std::max 函式:

    #include <iostream>
    #include <algorithm> // 包含 std::max 函式
    
    int main() {
        int numbers[] = {1, 2, 3, 4, 5};
        int max_value = *std::max_element(numbers, numbers + sizeof(numbers) / sizeof(int));
        std::cout << "The maximum value is: " << max_value << std::endl;
        return 0;
    }
  2. 使用 std::max_element 算法和指針:

    #include <iostream>
    #include <algorithm> // 包含 std::max_element 算法
    
    int main() {
        int numbers[] = {1, 2, 3, 4, 5};
        int* max_ptr = std::max_element(numbers, numbers + sizeof(numbers) / sizeof(int));
        int max_value = *max_ptr;
        std::cout << "The maximum value is: " << max_value << std::endl;
        return 0;
    }
  3. 使用循環遍歷數組:

    #include <iostream>
    
    int main() {
        int numbers[] = {1, 2, 3, 4, 5};
        int max_value = numbers[0];
        for (int i = 1; i < sizeof(numbers) / sizeof(int); i++) {
            if (numbers[i] > max_value) {
                max_value = numbers[i];
            }
        }
        std::cout << "The maximum value is: " << max_value << std::endl;
        return 0;
    }
  4. 使用STL std::vectorstd::max 函式:

    #include <iostream>
    #include <vector>
    #include <algorithm> // 包含 std::max 函式
    
    int main() {
        std::vector<int> numbers = {1, 2, 3, 4, 5};
        int max_value = *std::max_element(numbers.begin(), numbers.end());
        std::cout << "The maximum value is: " << max_value << std::endl;
        return 0;
    }
  5. 使用lambda表達式和std::max函式:

    #include <iostream>
    #include <vector>
    #include <algorithm> // 包含 std::max 函式
    
    int main() {
        std::vector<int> numbers = {1, 2, 3, 4, 5};
        int max_value = *std::max_element(numbers.begin(), numbers.end(),
                                         [](int a, int b) { return a < b; });
        std::cout << "The maximum value is: " << max_value << std::endl;
        return 0;
    }

以上代碼示例中,std::max_element 算法返回的是最大值的疊代器,std::max 函式則直接返回最大值。如果你使用的是C++11或更高版本,可以使用lambda表達式來定義比較函式。