Open In App

std::divides in C++

Improve
Improve
Like Article
Like
Save
Share
Report

Function object for performing division. Effectively calls operator / on two instances of type T.

Syntax :


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

Template Parameters :
T - Type of the arguments and return type of the functional call.
    The type shall support the operation (operator /).

Member types :
x : Type of the first argument in member operator()
y : Type of the second argument in member operator()
result_type : Type returned by member operator()

Example :




// C++ program to illustrate std::divides
// by dividing the respective elements of 2 arrays
#include <iostream> // std::cout
#include <functional> // std::divides
#include <algorithm> // std::transform
  
int main()
{
    // First array
    int first[] = { 10, 20, 30, 40, 50 };
  
    // Second array
    int second[] = { 1, 2, 3, 4, 5 };
  
    // Result array
    int results[5];
  
    // std::transform applies std::divides to the whole array
    std::transform(first, first + 5, second, results, std::divides<int>());
  
    // Printing the result array
    for (int i = 0; i < 5; i++)
        std::cout << results[i] << " ";
  
    return 0;
}


Output:

10 10 10 10 10

Another Example :




// C++ program to illustrate std::divides
// by dividing all array elements with a number
#include <bits/stdc++.h>
  
int main()
{
    // Array with elements to be divided
    int arr[] = { 10, 10 };
  
    // size of array
    int size = sizeof(arr) / sizeof(arr[0]);
  
    // Variable with which array is to be divided
    int num = 100;
  
    // Variable to store result
    int result;
  
    // using std::accumulate to perform division on array with num
    // using std::divides
    result = std::accumulate(arr, arr + size, num, std::divides<int>());
  
    // Printing the result
    std::cout << "The result of (100 / 10) / 10 is " << result;
  
    return 0;
}


Output:

The result of (100 / 10) / 10 is 1


Last Updated : 06 Aug, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads