×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

valarray abs() Function in C++ with Examples

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

The valarray class in C++ is a special container that is used for holding elements like an array and performing operations on them.

C++ STL std::abs(std::valarray) Function

The abs() function of the valarray class is used to calculate the absolute value of elements of valarray. It returns a valarray with each element calculated using the abs() function. The absolute value is the magnitude value of a number.

Syntax

template< class T >
valarray<T> abs( const valarray<T>& va );

// or
abs(valarrayName)

Parameter(s)

It accepts a single parameter which is the original valarray.

Return value

It returns a valarray with the absolute value of each element of the original valarray.

Example 1

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

int main()
{
    // Declaring valarray
    valarray<int> myvalarr = { 3, 6, 2, 5, 1 };

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

    // Creating a new valarray
    valarray<int> absValarray;
    absValarray = abs(myvalarr);

    cout << "\nThe elements of absolute valarray are : ";
    for (int& ele : absValarray)
        cout << ele << " ";

    return 0;
}

Output

The elements of orignal valarray are : 3 6 2 5 1 
The elements of absolute valarray are : 3 6 2 5 1 

Example 2

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

int main()
{
    // Declaring valarray
    valarray<double> myvalarr = { 3.1, -6, -0.2, 5, 1.7 };

    // Printing the elements of valarray
    cout << "The elements of orignal valarray are : ";
    for (double& ele : myvalarr)
        cout << ele << " ";

    // Creating a new valarray
    valarray<double> absValarray;
    absValarray = abs(myvalarr);

    cout << "\nThe elements of absolute valarray are : ";
    for (double& ele : absValarray)
        cout << ele << " ";

    return 0;
}

Output

The elements of orignal valarray are : 3.1 -6 -0.2 5 1.7 
The elements of absolute valarray are : 3.1 6 0.2 5 1.7 

Comments and Discussions!

Load comments ↻





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