valarray begin() Function in C++ with Examples

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

std::begin (valarray) Function

The valarray class in C++ is a special container that is used for holding elements like an array and performing operations on them. The begin() function in valarray is used to return an iterator which points to the element at the first index position.

Syntax:

template <class T> /*unspecified1*/ begin (valarray<T>& x);
template <class T> /*unspecified2*/ begin (const valarray<T>& x);

// or
begin(valarrayName)

Parameter(s): The function accepts the valarray whose iterator is to be returned.

Return Value: The method returns an iterator of the element of valarray.

C++ valarray begin() Function Example 1:

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

int main()
{
    // Declaring valarray
    valarray<int> myvalarr = { 1, 92, 13, 24, 55, 61, 7 };

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

    cout << "\nThe value returned by begin() function is " << begin(myvalarr);
    return 0;
}

Output:

The elements stored in valarray are : 1 92 13 24 55 61 7 
The value returned by begin() function is 0x55560b9a1eb0

You can extract the value from iterator using * operator. The below program display the working.

C++ valarray begin() Function Example 2:

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

int main()
{
    // Declaring valarray
    valarray<int> myvalarr = { 1, 92, 13, 24, 55, 61, 7 };

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

    cout << "\nThe value of element returned by begin() function is " << *begin(myvalarr);
    return 0;
}

Output:

The elements stored in valarray are : 1 92 13 24 55 61 7 
The value of element returned by begin() function is 1

The begin() method can also be used to iterate over the elements of the valarray.

C++ valarray begin() Function Example 3:

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

int main()
{
    // Declaring valarray
    valarray<int> myvalarr = { 1, 92, 13, 24, 55, 61, 7 };

    // Printing the elements of valarray
    cout << "The elements stored in valarray are : ";
    for (auto it = begin(myvalarr); it != end(myvalarr); it++) {
        cout << ' ' << *it;
    }
    return 0;
}

Output:

The elements stored in valarray are :  1 92 13 24 55 61 7




Comments and Discussions!

Load comments ↻






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