ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชันโมดูลัสใน C++
ฟังก์ชันโมดูลัส C++ คืออะไร
คลาสอ็อบเจ็กต์ฟังก์ชันโมดูลัสใน C++ ซึ่งกำหนดไว้ในไฟล์ส่วนหัว
รูปแบบของฟังก์ชันโมดูลัส
Template struct modulus : binary_function
{
T operator() (const T& a, const T& b) const {return a%b; }
}; พารามิเตอร์เทมเพลต
ฟังก์ชันยอมรับพารามิเตอร์ต่อไปนี้ −
-
ท − นี่คือประเภทของอาร์กิวเมนต์ที่ส่งผ่านไปยังการเรียกใช้ฟังก์ชัน
ตัวอย่าง
#include <iostream>
#include <algorithm>
#include <functional&g;
using namespace std;
int main(){
//create an array
int arr[] = { 10, 20, 35, 45, 50, 61 };
int rem[6];
transform(arr, arr + 6, rem,bind2nd(modulus<int>(), 2));
for (int i = 0; i < 5; i++){
cout << arr[i] << " is a "<<(rem[i] == 0 ? "even" : "odd")<<"\n";
}
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
10 is a even 20 is a even 35 is a odd 45 is a odd 50 is a even