How to get the first and last elements of an array in C++ STL?

C++ STL | getting first and last elements of an array: Here, we are going to learn how to get the first and last elements of an array using different methods in C++ STL?
Submitted by IncludeHelp, on February 28, 2019

Given an array and we have to access its first and last elements in C++ STL.

Getting first and last elements of an array

There are two common and popular ways to get the first and last elements of an array,

  1. Using array::operator[]
  2. Using array::front() and array::back() functions

1) Using array::operator[]

Operator[] requires an index and it returns reference to that index, thus, to get the first element of an array, we use 0 as an index (as we know that array index starts with 0) and to get the last element, we use array::size() function it returns the total number of elements, thus, to get the last element of an array, we use array::size()-1 as an index.

2) Using array::front() and array::back() functions

array::front() function returns a reference to the first element and array::back() function returns a reference to the last element of an array.

Example:

    Input or array declaration:
    array<int,5> values {10, 20, 30, 40, 50};

    Method 1:
    To get first element: values[0] = 10
    To get the last element: values[values.size()-1] = 50

    Method 2:
    To get the first element: values.front() = 10
    To get the last element: values.back() = 50

C++ STL program to get the first and last elements of an array

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

int main()
{
	array<int,5> values {10, 20, 30, 40, 50};

	//by using operator[]
	cout<<"First element is: "<<values[0]<<endl;
	cout<<"Last element is:  "<<values[values.size()-1]<<endl;

	//by using front() and back() function
	cout<<"First element is: "<<values.front()<<endl;
	cout<<"Last element is:  "<<values.back()<<endl;    

	return 0;
}

Output

First element is: 10
Last element is:  50
First element is: 10
Last element is:  50




Comments and Discussions!

Load comments ↻






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