Home »
C++ STL
valarray end() Function in C++ with Examples
C++ valarray end() Function: Here, we will learn about the end() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on May 07, 2022
C++ STL std::end (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 end() function in valarray is used to return an iterator which points to the element next to the element at the last index position.
Syntax
template <class T> /*unspecified1*/ end (valarray<T>& x);
template <class T> /*unspecified2*/ end (const valarray<T>& x);
// or
end(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 end() function is " << end(myvalarr);
return 0;
}
Output
The elements stored in valarray are : 1 92 13 24 55 61 7
The value returned by end() function is 0x55a21c4bdecc
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 returned by end() function is " << *(end(myvalarr) - 1);
return 0;
}
Output
The elements stored in valarray are : 1 92 13 24 55 61 7
The value returned by end() function is 7
Here, we have added "-1" so that the last element can be returned denoting the function functionality. The value with -1 would be 0.
The end() method can also be used to iterate over the elements of the valarray along with begin() method.
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