類模板
<functional>

std::modulus

template <class T> struct modulus;
Modulus 函式物件類
其呼叫返回其兩個引數的模運算結果(由 operator % 返回)的二元函式物件類。

泛指,函式物件 是一個類的例項,該類定義了成員函式operator()。這個成員函式允許物件以與函式呼叫相同的語法使用。

它的定義與以下行為相同:

1
2
3
template <class T> struct modulus : binary_function <T,T,T> {
  T operator() (const T& x, const T& y) const {return x%y;}
};
1
2
3
4
5
6
template <class T> struct modulus {
  T operator() (const T& x, const T& y) const {return x%y;}
  typedef T first_argument_type;
  typedef T second_argument_type;
  typedef T result_type;
};

此類物件可用於標準演算法,例如 transformaccumulate

模板引數

T
函式呼叫引數和返回值的型別。
該型別應支援運算(operator%)。

成員型別

成員型別定義說明
first_argument_typeT成員 operator() 的第一個引數的型別
second_argument_typeT成員 operator() 的第二個引數的型別
result_typeT成員 operator() 返回的型別

成員函式

T operator() (const T& x, const T& y)
成員函式,返回其引數之間的模運算(x%y)。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
// modulus example
#include <iostream>     // std::cout
#include <functional>   // std::modulus, std::bind2nd
#include <algorithm>    // std::transform

int main () {
  int numbers[]={1,2,3,4,5};
  int remainders[5];
  std::transform (numbers, numbers+5, remainders, std::bind2nd(std::modulus<int>(),2));
  for (int i=0; i<5; i++)
    std::cout << numbers[i] << " is " << (remainders[i]==0?"even":"odd") << '\n';
  return 0;
}

輸出

1 is odd
2 is even
3 is odd
4 is even
5 is odd


另見