×

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an iterator to the last entry.

Syntax:

list_name. back ()

Parameters

This function doesn't accept any parameters.

Return Value: This function directly references the last element in the list container example list. Although this function does not contain such an exception, applying it on a list container that is empty results in an undefined behaviour in C++.

Errors and Exception

  1. When the list container is empty, it shows unknown behaviour results.
  2. It ensures that no exceptions will be thrown, if the list is not empty.
// C++ program of list back() function 
#include <iostream>
#include <list>
usingnamespacestd;
 
intmain()
{
    list<int>mylist{ 1, 2, 3, 4, 5 };
    cout<<mylist.back();
    return0;
}

Output:

List back () function in C++ STL

The list::back() function is illustrated in the program below.

// assign() method for lists
#include <bits/stdc++.h>
usingnamespacestd;
 
intmain()
{
    // list creation from scratch
    list<int>demo_list;
 
    // Including more items to the list
    demo_list.push_back(10);
    demo_list.push_back(20);
    demo_list.push_back(30);
 
    // prints the last element of demo_list
    cout<<demo_list.back();
 
    return0;
}

Output:

List back () function in C++ STL

Time Complexity: O(1)

Auxiliary Space: O(1)

Application

Print the difference between the first and last entry after adding numbers to an empty list of integers.

Input: 1,2,3,4,5,6,7,8

Output: 7

Explanation: final component =8, initial component=1, difference=7

Algorithm

  1. Using the push front() or push back() function, add numbers to the list.
  2. Compare the first and last components.
  3. Subtract the last element from the first element if it is larger, then print the result.
  4. Otherwise, divide the first element by the last element and output the result.


Code:

// CPP programme to exemplify
// application of the functions front() and back()
#include <iostream>
#include <list>
usingnamespacestd;
 
intmain()
{
    list<int>mylist{};
    mylist.push_front(8);
    mylist.push_front(7);
    mylist.push_front(6);
    mylist.push_front(5);
    mylist.push_front(4);
    mylist.push_front(3);
    mylist.push_front(2);
    mylist.push_front(1);
 
    // listing is now 1, 2, 3, 4, 5, 6, 7, and 8.
 
    if(mylist.front() >mylist.back()) {
        cout<<mylist.front() - mylist.back();
    }
    elseif(mylist.front() <mylist.back()) {
        cout<<mylist.back() - mylist.front();
    }
    else
        cout<< "0";
}

Output:

List back () function in C++ STL

Related Topics

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

Dynamic Memory Allocation in C++

In some programming situations, the number of data items changes as the program is running, which is known as dynamic data or input. Consider a real-world situation where a program...

3 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton...

2 minutes read.

Is it fine to write void main() or main() in C/C++?

In C programming language: The default function return type in the C programming language is "int," which implies that main() will always return an integer value. In C, the void main()...

3 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of...

3 minutes read.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

How to create a library in C++

Before going on to the creation of a library, let’s understand its meaning. What is a library? In simple words, a library is a collection of numerous functions, methods, classes, header files...

7 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

How to enter a name in C++

A name is a string or array of characters or letters. The string is one of the most helpful data types offered by the C++ library. A string helps the...

4 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.