Home »
C++ STL
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
C++ STL 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.
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.
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.
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