在本文中,我们将讨论C ++中模数函数的工作,语法和示例。
C ++中的模数函数对象类,在<functional>头文件中定义。模数函数是一个二进制函数对象类,用于获取两个参数的模数运算的结果。此功能与运算符'%'相同。
Template struct modulus : binary_function
{
   T operator() (const T& a, const T& b) const {return a%b; }
};该函数接受以下参数-
T-这是传递给函数调用的参数的类型。
#include <iostream>
#include <algorithm>
#include <functional&g;
using namespace std;
int main(){
   //创建一个数组
   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