C++最小值

在C++中,你可以使用STL(標準模板庫)中的std::min函式來找到兩個或多個值中的最小值。這個函式會返回其參數列表中的最小值。下面是一個簡單的例子:

#include <iostream>
#include <algorithm> // 包含std::min函式

int main() {
    int a = 10;
    int b = 20;
    int c = 30;

    auto min_val = std::min(a, b); // 比較a和b,並返回最小值
    std::cout << "The minimum of " << a << " and " << b << " is " << min_val << std::endl;

    min_val = std::min(min_val, c); // 比較min_val和c,並返回最小值
    std::cout << "The minimum of " << min_val << " and " << c << " is " << min_val << std::endl;

    // 如果你有多個值,也可以直接比較
    auto values = {100, 200, 300, 10};
    min_val = *std::min_element(values.begin(), values.end());
    std::cout << "The minimum of the values is " << min_val << std::endl;

    return 0;
}

在這個例子中,我們首先比較了ab,並使用std::min函式返回了最小值。然後,我們將這個最小值與c進行比較,再次使用std::min函式返回新的最小值。最後,我們比較了一個整數數組中的所有值,並使用std::min_element函式找到最小值,然後使用*解引用運算符來獲取最小值本身。

如果你想要在自定義的容器中找到最小值,你可以使用std::min_element函式,它會返回最小值的疊代器,然後你可以使用解引用運算符來獲取最小值本身。