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