class template

std::modulus

<functional>
template <class T> struct modulus;
Modulus function object class
This class defines function objects for the modulus arithmetic operation.

Generically, function objects are instances of a class with member function operator() defined. This member function allows the object to be used with the same syntax as a regular function call, and therefore it can be used in templates instead of a pointer to a function.

modulus has its operator() member defined such that it returns the remainder of dividing its first argument by the second (i.e., its modulus). For negative values, the result may vary depending on the library implementation.

This class is derived from binary_function and is defined as:

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


Objects of this class can be used with some standard algorithms such as transform or accumulate.

Members

T operator() (const T& x, const T& y)
Member function returning x%y.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// modulus example
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;

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


Output:

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

See also