有没有一种干净快速的方法来查找数组的最小值和最大值

Eri*_*c V -4 c++ arrays

有没有一种干净快速的方法来查找数组的最小值和最大值

int array1[] = {2,6,10,22,12};

结果是

最小值 = 2 / 最大值 = 22

// Function  
void min_max(set<int> my_set) 
{ 
    for (auto i : my_set); 
} 

// Function to find the maximum element 
int findMax(set<int> my_set) 
{ 

    // Get the maximum element 
    int max_element; 
    if (!my_set.empty()) 
        max_element = *(my_set.rbegin()); 

    // return the maximum element 
    return max_element; 
} 

// Function to find the minimum element 
int findMin(set<int> my_set) 
{ 

    // Get the minimum element 
    int min_element; 
    if (!my_set.empty()) 
        min_element = *my_set.begin(); 

    // return the minimum element 
    return min_element; 
} 

int main() 
{ 

    // Get the set 
    set<int> my_set = {2,6,10,22,12}; 
        // results
        findMin(my_set) 
        findMax(my_set) 
        
} 
Run Code Online (Sandbox Code Playgroud)

Joh*_*eau 5

不要重新发明轮子。C++ 标准库的存在是为了使常见的编程任务花费很少的时间,并且出错的可能性很小。

你想要std::min_elementstd::max_element。您需要包含<algorithm>才能使用这些。

#include <algorithm> // for min/max_element
#include <iterator>  // for begin/end

...

int array1[] = {2,6,10,22,12};

int min = std::min_element(std::begin(array1), std::end(array1));
int max = std::max_element(std::begin(array1), std::end(array1));
Run Code Online (Sandbox Code Playgroud)

这些函数的文档可以在以下页面找到:

https://en.cppreference.com/w/cpp/algorithm/min_element
https://en.cppreference.com/w/cpp/algorithm/max_element
https://en.cppreference.com/w/cpp/iterator/开始

如果您想要真正喜欢,您可以使用std::minmaxwithstd::tie来打开std::pair返回的包装。

#include <algorithm> // for minmax_element
#include <iterator>  // for begin/end
#include <tuple>     // for tie

...

int array1[] = {2,6,10,22,12};

int min, max;
std::tie(min, max) = std::minmax_element(std::begin(array1), std::end(array1));
Run Code Online (Sandbox Code Playgroud)

https://en.cppreference.com/w/cpp/algorithm/minmax_element
https://en.cppreference.com/w/cpp/utility/tuple/tie

  • 还有 [`std::minmax_element()`](https://en.cppreference.com/w/cpp/algorithm/minmax_element)。并且 C++17 中不需要 `std::tie()` ,您可以使用[结构化绑定](https://en.cppreference.com/w/cpp/language/structured_binding)代替。 (2认同)