C++ STL 中的取模函数
在本文中,我们将讨论 C++ 中取模函数的函数工作原理、语法和示例。
什么是 C++ 取模函数?
modulus function 在 C++ 中是一个对象函数类,它定义在 <functional> 头文件中。modulus function 是一个二元函数对象类,用于获取两个参数取模运算的结果。此函数的工作原理与运算符“%”相同。
取模函数语法
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(){
//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
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP