×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

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

Problem statement

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

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.

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.