std::plus in c++
Last Updated :
26 Jul, 2017
It is a Function object for performing addition. The object class whose call returns the result of adding its two arguments (as returned by operator + ).
Syntax :
template struct plus : 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()
#include <iostream> // std::cout
#include <functional> // std::plus
#include <algorithm> // std::transform
int main()
{
int first[] = { 1, 2, 3, 4, 5 };
int second[] = { 10, 20, 30, 40, 50 };
int results[5];
std::transform(first, first + 5, second, results, std::plus< int >());
for ( int i = 0; i < 5; i++)
std::cout << results[i] << " " ;
return 0;
}
|
Output:
11 22 33 44 55
Another example:
#include <bits/stdc++.h>
int main()
{
int arr[] = { 10, 20, 30 };
int size = sizeof (arr) / sizeof (arr[0]);
int num = 100;
int result;
result = std::accumulate(arr, arr + size, num, std::plus< int >());
std::cout << "The result of 100 + 10 + 20 + 30 is " << result;
return 0;
}
|
Output:
The result of 100 + 10 + 20 + 30 is 160
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...