C/C++ 3個求最大值的方法

本篇介紹 C/C++ 3 個求最大值的方法,分別為兩數求最大值、傳統陣列求最大值以及 C++ vector 求最大值。

兩數求最大值的方法

以下為兩數中求最大值的方法,要自己寫一個 max 函式也不是不行,只是如果想快速開發的話,使用 std::max 會方便快速些,不需要遇到每種類型的 max 都要寫一遍,使用 std::max 即可應付各種變數類型,

cpp-find-max-value.cpp
1
2
3
4
5
6
7
8
9
10
11
12
// g++ cpp-find-max-value.cpp -o a.out
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
cout << std::max(3, 5) << "\n";
cout << std::max(10, 6) << "\n";
cout << std::max(15.6f, 17.1f) << "\n";
return 0;
}

輸出:

1
2
3
5
10
17.1

以上面的例子,整數與浮點數都能處理,
關於 C++ std::max 的更詳細的用法與範例可參考我之前寫的這篇

傳統陣列求最大值的方法

以下為標準 C 在陣列中求最大值的方法,
一開始準備好一個陣列後,接下來就是在這個陣列中找出最大值,先將 max 值等於陣列的第一個值,如果一路尋找下來都沒有比這個值還大的話,那麼它就是最大值。

接下來用迴圈在 num 裡尋找有沒有比當前的 max 值還要大的數值,有的話就更新一下目前最大的 max 值。

等到迴圈迭代完後,該 max 值就是這個陣列中的最大值了。

cpp-find-max-value2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// g++ cpp-find-max-value2.cpp -o a.out
#include <iostream>

using namespace std;

int main() {
int num[6] = {4,2,-6,5,1,3};
int max = num[0];
for (int i=1; i<6; i++) {
if (num[i] > max)
max = num[i];
}
cout << "max: " << max << "\n";
return 0;
}

輸出:

1
max: 5

C++ vector 求最大值的方法

以下為 C++ vector 求最大值的方法,使用 C++ 的好處是內建的 STL 有很多函式庫供你使用,但前提是要會使用,就像有車子可開但不會開車也是枉然,但學會開車能讓你比起走路或騎車達到目的地的時間大幅縮短,寫程式遇到要急迫快速開發的情況時,這時對於 STL 的掌握精準度就變得很重要,以下就來示範使用 C++ std::max_element 在 vector 容器裡求最大值,

宣告好 vector 容器並初始化填好元素後,使用 std::max_element 並指定範圍是 v 的最頭部到最尾部,完畢後的 result 迭代器就是指向最大值的元素了,

cpp-find-max-value3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// g++ cpp-find-max-value3.cpp -o a.out -std=c++11
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
std::vector<int> v{4,2,-6,5,1,3};
std::vector<int>::iterator result;

result = std::max_element(v.begin(), v.end());
std::cout << "max element: " << *result << "\n";
return 0;
}

輸出結果同上。

以上就是 C/C++ 3個求最大值的方法介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!
關於 C++ std::max_element 更詳細的用法與範例請看這篇

其他參考
std::max_element - cppreference.com
https://en.cppreference.com/w/cpp/algorithm/max_element
max_element - C++ Reference
http://www.cplusplus.com/reference/algorithm/max_element/
c++ - std::array finding max value function - Stack Overflow
https://stackoverflow.com/questions/33344566/stdarray-finding-max-value-function

其它相關文章推薦
C/C++ 新手入門教學懶人包
std::max_element 用法與範例
std::max 用法與範例
C++ virtual 的兩種用法
C/C++ 字串反轉 reverse
C/C++ call by value傳值, call by pointer傳址, call by reference傳參考 的差別
C++ 類別樣板 class template
std::sort 用法與範例
std::find 用法與範例
std::queue 用法與範例
std::map 用法與範例