C++ Standard Library C++ STL Library

C++ <valarray> - apply() Function



The C++ valarray::apply function returns a new valarray of the same size with elements as a result of applying function func to its corresponding element in the given valarray.

Syntax

valarray apply (T func(T)) const;
valarray apply (T func(const T&)) const;

Parameters

func Specify function to apply to every elements of the valarray.

Return Value

Returns valarray with values as a result of applying function func.

Time Complexity

Depends on library implementation.

Example:

The example below shows the usage of valarray::apply function.

#include <iostream>
#include <valarray>
using namespace std;
 
int increment (int x) {return ++x;}
int decrement (int x) {return --x;}

int main (){
  valarray<int> varr = {10, 20, 30, 40, 50};

  cout<<"varr contains: ";
  for(int i = 0; i < varr.size(); i++)
    cout<<varr[i]<<" "; 

  valarray<int> result1 = varr.apply(increment);
  cout<<"\nvarr.apply(increment) returns: ";
  for(int i = 0; i < result1.size(); i++)
    cout<<result1[i]<<" "; 

  valarray<int> result2 = varr.apply(decrement);
  cout<<"\nvarr.apply(decrement) returns: ";
  for(int i = 0; i < result2.size(); i++)
    cout<<result2[i]<<" "; 

  return 0;
}

The output of the above code will be:

varr contains: 10 20 30 40 50 
varr.apply(increment) returns: 11 21 31 41 51 
varr.apply(decrement) returns: 9 19 29 39 49 

❮ C++ <valarray> Library

5