Modulus function in C++ STL

C++Server Side ProgrammingProgramming

In this article, we will be discussing the working, syntax, and examples of modulus functions in C++.

What is modulus function C++?

modulus function object class in C++, which is defined in <functional> header file. modulus function is a binary function object class used to get the result of the modulus operation of the two arguments. This function works the same as the operator ‘% ‘.

Syntax of modulus function

Template struct modulus : binary_function
{
   T operator() (const T& a, const T& b) const {return a%b; }
};

Template parameters

The function accepts the following parameter(s) −

  • T − This is the type of the argument passed to function call.

Example

 Live Demo

#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;
}

Output

If we run the above code it will generate the following output −

10 is a even
20 is a even
35 is a odd
45 is a odd
50 is a even
raja
Updated on 22-Apr-2020 12:44:17

Advertisements