Home » C++ STL

How to get the first and element 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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.