C++ back() function
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
- 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
#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
The C++ container class