The apply() function is defined in valarray header file. This function returns a valarray with each of its elements initialized to the result of applying func to its corresponding element in *this.
Syntax:
valarray apply (T func(T)) const; valarray apply (T func(const T&)) const;
Parameter: This method accepts a mandatory parameter func which represents the pointer to the function taking an argument of type T.
Return Value: This method returns a valarray object with the results of applying func to all the elements of *this.
Below programs illustrate the above function:
Example 1:-
// C++ program to demonstrate // example of apply() function. #include <bits/stdc++.h> using namespace std;
int main()
{ // Initializing valarray
valarray< int > varr = { 15, 10, 30, 33, 40 };
// Declaring new valarray
valarray< int > varr1;
// Using apply() to increment all elements by 5
varr1 = varr.apply([]( int x) { return x = x + 5; });
// Displaying new elements value
cout << "The new valarray "
<< "with manipulated values is : " ;
for ( int & x : varr1)
cout << x << " " ;
cout << endl;
return 0;
} |
Output:
The new valarray with manipulated values is : 20 15 35 38 45
Example 2:-
// C++ program to demonstrate // example of apply() function. #include <bits/stdc++.h> using namespace std;
int main()
{ // Initializing valarray
valarray< int > varr = { 15, 10, 30, 33, 40 };
// Declaring new valarray
valarray< int > varr1;
// Using apply() to decrement all elements by 5
varr1 = varr.apply([]( int x) { return x = x - 5; });
// Displaying new elements value
cout << "The new valarray"
<< " with manipulated values is : " ;
for ( int & x : varr1)
cout << x << " " ;
cout << endl;
return 0;
} |
Output:
The new valarray with manipulated values is : 10 5 25 28 35