ใช้ฟังก์ชัน max_element() จาก <algorithm> หาค่าสูงสุดในอาร์เรย์ คืนค่า Iterator ต้อง Dereference เพื่อได้ค่า
ตัวอย่างโค้ด
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {12, 45, 74, 32, 66, 96, 21, 32, 27};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Array is like: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\nMax Element is: " << *max_element(arr, arr + n);
return 0;
}
ผลลัพธ์
Array is like: 12 45 74 32 66 96 21 32 27 Max Element is: 96
การใช้งานเพิ่มเติม
// หาค่าสูงสุดใน Vector vectorv = {3, 1, 4, 1, 5}; auto it = max_element(v.begin(), v.end()); // ใช้ Comparator แบบกำหนดเอง struct Point { int x, y; }; vector pts = {{1,2}, {3,4}, {0,5}}; auto maxPt = max_element(pts.begin(), pts.end(), [](const Point& a, const Point& b) { return a.x < b.x; });