Modulus function in C++ STL

Modulus function is used to return the value of the modulus between its two arguments. It works same as modulus operator works.

template  struct modulus : binary_function  
{
  T operator() (const T& x, const T& y) const 
  {
   return x%y;
  }
};

Member types:

  • Type of first argument
  • Type of second argument
  • Type of result returned by member operator

Note: We must include library ‘functional’ and ‘algorithm’ to use modulus and transform.



Bewlo programs illustrate the working of modulus function:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

8 is a even
6 is a even
3 is a odd
4 is a even
1 is a odd
filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

0 1 0 1 0 1 0 1 0 1


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.