Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ back() function

C++ back() function

C++ Container Class The C++ container class


back is used in list toget the last element.

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

The time complexity is O(1).

Word meaning: back means "back," i.e., to get the last element.


Basic syntax and parameters

Syntax format



reference back();

const_reference back() const;

Function description


Example

Example 1: Get the last element

Example

#include

#include

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

<<

"Modified last element: "

<<

numbers.

back

(

)

<<

std

::

endl

;

   

return

0

;

}

Expected output:

最后一个元素: 50

修改后最后一个元素: 100


C++ Container Class The C++ container class