模量函數用於返回其兩個參數之間的模量值。它的作用與模運算符的作用相同。
template struct modulus : binary_function { T operator() (const T& x, const T& y) const { return x%y; } };
會員類型:
- 第一個參數的類型
- 第二個參數的類型
- 成員運算符返回的結果類型
注意:我們必須包括庫“ functional”和“ algorithm”,以使用模數和變換。
Bewlo程序說明了模函數的作用:
// C++ program to implement modulus function
#include <algorithm> // transform
#include <functional> // modulus, bind2nd
#include <iostream> // cout
using namespace std;
int main()
{
// defining the array
int array[] = { 8, 6, 3, 4, 1 };
int remainders[5];
// transform function that helps to apply
// modulus between the arguments
transform(array, array + 5, remainders,
bind2nd(modulus<int>(), 2));
for (int i = 0; i < 5; i++)
// printing the results while checking
// whether no. is even or odd
cout << array[i] << " is a "
<< (remainders[i] == 0 ? "even" : "odd")
<< endl;
return 0;
}
輸出:
8 is a even 6 is a even 3 is a odd 4 is a even 1 is a odd
// C++ program to implement modulus function
#include <algorithm> // transform
#include <functional> // modulus, bind2nd
#include <iostream> // cout
#include <iterator>
#include <vector>
using namespace std;
int main()
{
// Create a std::vector with elements
// {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
vector<int> v;
for (int i = 0; i < 10; ++i)
v.push_back(i);
// Perform a modulus of two on every element
transform(v.begin(), v.end(), v.begin(),
bind2nd(modulus<int>(), 2));
// Display the vector
copy(v.begin(), v.end(),
ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
輸出:
0 1 0 1 0 1 0 1 0 1
相關用法
- C++ log()用法及代碼示例
- C++ div()用法及代碼示例
- C++ fma()用法及代碼示例
- C++ map key_comp()用法及代碼示例
- C++ valarray pow()用法及代碼示例
- C++ valarray log()用法及代碼示例
- C++ regex_iterator()用法及代碼示例
- C++ map rbegin()用法及代碼示例
- C++ valarray end()用法及代碼示例
注:本文由純淨天空篩選整理自shubham tyagi 4大神的英文原創作品 Modulus function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。