C++ <list> back function

C++ container class <list>


backis used in list toget the last elementof the function.

backIs a member function of the container class, used to return the last element of the linked list.

The time complexity is O(1).

Word Definitions: backMeans "back", i.e., obtains the last element.


Basic syntax and parameters

Syntax format

reference back();
const_reference back() const;

Function description

  • Return Value: Returns a reference to the last element.
  • Note: The linked list must not be empty.

Example

Example 1: Get the last element

Example

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = {10, 20, 30, 40, 50};

    std::cout << "Last element: " << numbers.back() << std::endl;

    // Modify the last element
    numbers.back() = 100;
    std::cout << "Last element after modification: " << numbers.back() << std::endl;

    return 0;
}

Expected running result:

最后一个元素: 50
修改后最后一个元素: 100

C++ container class <list>

other extensions