valarray apply() Function in C++ with Examples

C++ valarray apply() Function: Here, we will learn about the apply() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on May 07, 2022

std::valarray<T>::apply() Function

The valarray class contains many utility functions to perform tasks on the valarray elements. The apply() function in the valarray class is used to apply a manipulation operation to all the elements of the valarray.

The manipulation operation is specified as the argument to the function. It returns a new valarray with elements updated using the given manipulation operation on the elements of the original valarray.

Syntax:

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

// or
valarrayName.apply([] (int ele){// manipulation operation of ele})

Parameter(s): The parameter of the function in the manipulation operation.

Return Value: The function returns a new valarray with updated elements.

C++ valarray apply() Function Example 1:

#include <iostream>
#include <valarray>
using namespace std;

int main()
{
    // Declaring valarray
    valarray<int> myvalarr = { 5, 7, 2, 8, 1, 9 };

    // Printing the elements of valarray
    cout << "The elements stored in valarray are : ";
    for (int& ele : myvalarr)
        cout << ele << " ";

    // Updating the elements of valarray using apply method
    valarray<int> updateValArr;
    updateValArr = myvalarr.apply([](int val) { return val = val * val; });

    // Printing the elements of new valarray
    cout << "\nThe updated elements of valarray are : ";
    for (int& ele : updateValArr)
        cout << ele << " ";

    return 0;
}

Output:

The elements stored in valarray are : 5 7 2 8 1 9 
The updated elements of valarray are : 25 49 4 64 1 81

C++ valarray apply() Function Example 2:

#include <iostream>
#include <valarray>
using namespace std;

int myfunc(int n)
{
    int i, fact = 1;

    for (i = n; i >= 1; i--)
        fact = fact * i;

    return fact;
}

int main()
{
    // Declaring valarray
    valarray<int> myvalarr = { 9, 8, 7, 6, 5 };

    // Printing the elements of valarray
    cout << "The elements stored in valarray are : ";
    for (int& ele : myvalarr)
        cout << ele << " ";

    // Updating the elements of valarray using apply method
    valarray<int> updateValArr;
    updateValArr = myvalarr.apply([](int n) -> int { myfunc(n); });

    // Printing the elements of new valarray
    cout << "\nThe updated elements of valarray are : ";
    for (int& ele : updateValArr)
        cout << ele << " ";

    return 0;
}

Output:

The elements stored in valarray are : 9 8 7 6 5 
The updated elements of valarray are : 362880 40320 5040 720 120



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.