Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน max() สำหรับ valarray ใน C++

ในบทความนี้ เราจะอภิปรายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน valarray::max() ใน C++ STL

valarray คืออะไร?

std::valarray เป็นคลาสที่ใช้สำหรับแทนค่า แก้ไขอาร์เรย์ของค่า ซึ่งรองรับการดำเนินการทางคณิตศาสตร์แบบ element-wise

valarray::max() คืออะไร?

ฟังก์ชัน std::valarray::max() เป็นฟังก์ชันสำเร็จรูปใน C++ STL ซึ่งถูกกำหนดในไฟล์หัวข้อ <valarray> ฟังก์ชันนี้ส่งคืนค่าสูงสุดที่อยู่ใน valarray container

หาก valarray ว่าง ผลลัพธ์ที่ส่งคืนจะเป็น unspecified

ไวยากรณ์

V_array_name.max();

พารามิเตอร์

ฟังก์ชันไม่ยอมรับพารามิเตอร์ใดๆ

ค่าที่ส่งคืน

ฟังก์ชันนี้ส่งคืนค่าสูงสุดของ valarray

ตัวอย่าง

Input

valarray<int> arr = { 1, 2, 4, 5, 8, 9 }; arr.max();

Output

9

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

int main() {
    valarray<int> arr = {2, 4, 6, 8, 10};
    cout << "Largest element is = "; cout << arr.max() << endl;
    return 0;
}

ผลลัพธ์

Largest element is = 10

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

int main() {
    valarray<int> arr = {2, 4, 6, 10, 10};
    // หารากที่สองของตัวเลขที่มากที่สุด
    int product = arr.max() * arr.max();
    cout << "Square root of greatest number is: " << product;
    return 0;
}

ผลลัพธ์

Square root of greatest number is: 100