std::valarray class in C++ and its methods

Here we will learn about std::valarray class in C++. A valarray is for holding an array of values and for performing mathematical functions on the arrays. It performs element-wise operations. This is efficient than vectors in terms of mathematical operations. Most of the mathematical operations can be applied directly to valarry objects, which are arithmetical and comparison operators. It allows libraries for some optimizations like memory recycling, copy-on-write optimizations.

Member functions of valarry class

1.apply(): Manipulation in its arguments to all the valarray elements at one time then returns a new valarray that holds manipulated values.

2.sum(): Summations of all the elements in the valarray at one time.

3.min(): Smallest element present in valarray.

4.max(): Largest element present in valarray.

5. shift(): It gives a new valarray after shifting of the elements by the number given in argument. If the number is negative, it will shift the right side and if the number is positive it will shift the left side.

6.cshift(): It gives a new valarray after a rotation of elements by the number given in argument. If the number is negative, it will shift the right circular side and if the number is positive it will shift the left circular side.

7.swap(): Swaps the valarray.

 

Let us look at an example that will provide the largest and smallest element:

#include<iostream> 
#include<valarray> 
using namespace std; 
int main() 
{ 
   
    valarray<int> v = { 1, 27, 209, 14, 3 }; 
      
    
    cout << "print the largest one : "; 
    cout << v.max() << endl; 
      
    
    cout << "print the smallest one : "; 
    cout << v.min() << endl; 
  
    return 0; 
      
}

So, This was a summarization of the std::valarray class in C++ and its various methods involved.

Also read: Initialization of multidimensional array of zeros using C++

Leave a Reply

Your email address will not be published. Required fields are marked *