×

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 sum() Function in C++ with Examples

C++ valarray sum() Function: Here, we will learn about the sum() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on May 08, 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::valarray<T>::sum() Function

The sum() function is defined in valarray class, and it returns the sum of all the elements of the valarray, as if calculated by applying operator+= to a copy of one element and all the other elements, in an unspecified order.

Syntax

T sum() const;

// or
valarray.sum()

Parameter(s)

The method does not require any parameter.

Return value

The method returns a single value with the same type as the element of the valarray.

Example 1

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

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

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

    // Calculating the sum of all elements of valarray
    cout << "\nThe sum of all elements of valarray is ";
    cout << myvalarr.sum();
    
    return 0;
}

Output

The elements stored in valarray are : 1 2 3 4 5 6 7 
The sum of all elements of valarray is 28

Example 2

// Program to find the type of summed value

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

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

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

    // Calculating the sum of all elements of valarray
    cout << "\nThe type of summed values is ";
    cout << typeid(myvalarr.sum()).name();
    
    return 0;
}

Output

The elements stored in valarray are : 1 2 3 4 5 6 7.4 
The type of summed values is f

Comments and Discussions!

Load comments ↻





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