C++ back() function
Among the various operations on vector,back is a very practical function, used toget the last element.
back is a member function of the container class, used toreturns the last element of the container. It is equivalent to at(size()-1) or operator[](size()-1), but with clearer semantics.
back provides an intuitive way to access the last element of the container, often used in implementing data structures such as stacks and queues.
Word meaning: back means 'back', i.e., to get the last (rearmost) element.
Basic syntax and parameters
back is a member function of the container class; calling it is straightforward and requires no arguments.
Syntax format
reference back();
const_reference back() const;
Parameter Description
- Parameters: No parameters
backtakes no arguments.
Function description
- Return Value: Returns thereferenceto the element at the specified position. If the container is const, a const reference is returned.
- effect: Returns the last element of the container (index
size()-1element). - Note: Before calling
back, ensure the container is not empty; otherwise the behavior is undefined. It is recommended to first useempty()orsize() > 0to check.
Example
Let us thoroughly master back through a series of examples from simple to complex.
Example 1: Basic usage - getting the last element
Example
#include
#include
int
main
(
)
{
// 1. Create a vector and add some elements
std
::
vector
<
int
numbers
=
{
10
,
20
,
30
,
40
,
50
};
std
::
cout
<<
"vector size is: "
<<
numbers.
size
(
)
<<
std
::
endl
;
// 2. Use back to get the last element
std
::
cout
<<
"Last element (back): "
<<
numbers.
back
(
)
<<
std
::
endl
;
std
::
cout
<<
"Using at(size()-1): "
<<
numbers.
at
(
numbers.
size
(
)
1
)
<<
std
::
endl
;
std
::
cout
<<
"Using [size()-1]: "
<<
numbers
[
numbers.
size
(
)
1
]
<<
std
::
endl
;
return
0
;
}
Expected output:
vector的大小是: 5
最后一个元素 (back): 50
使用 at(size()-1): 50
使用 [size()-1]: 50
Code analysis:
numbers.back()returns the last element50.- It returns the same value as
numbers.at(numbers.size()-1)andnumbers[numbers.size()-1], but with clearer semantics.
Example 2: Modifying the last element's value
back returns a reference, so it can be used to modify the element's value.
Example
#include
#include
#include
int
main
(
)
{
std
::
vector
<
std
::
string
tasks
=
{
"Learn C++"
,
"Do homework"
,
"Read documentation"
}
;
std
::
cout
<<
"Before modification, last task: "
<<
tasks.
back
(
)
<<
std
::
endl
;
// Use back() to get a reference and modify the element
tasks.
back
(
)
=
"Complete project"
;
std
::
cout
<<
"After modification, last task: "
<<
tasks.
back
(
)
<<
std
::
endl
;
// Now the content of tasks is: Learn C++, do homework, complete project
return
0
;
}
Expected output:
修改前,最后一个任务: 阅读文档
修改后,最后一个任务: 完成项目
Code analysis:
tasks.back() = "完成项目";modified the value of the last element through the reference.back()returns a modifiable lvalue reference.
Example 3: Safe use of back - check whether the container is empty
When using back Before using, you should first check whether the container is empty.
Example
#include
#include
void
printBack
(
const
std
::
vector
<
int
&
v
)
{
if
(!
v.
empty
(
)
)
{
std
::
cout
<<
"The last element is: "
<<
v.
back
(
)
<<
std
::
endl
;
}
else
{
std
::
cout
<<
"Container is empty; cannot get the last element"
<<
std
::
endl
;
}
}
int
main
(
)
{
std
::
vector
<
int
numbers
=
{
10
,
20
,
30
};
// Normal case
printBack
(
numbers
)
;
// Empty container case
std
::
vector
<
int
emptyVec;
printBack
(
emptyVec
)
;
return
0
;
}
Expected output:
最后一个元素是: 30
容器为空,无法获取最后一个元素
Code analysis:
!v.empty()Check whether the container is not empty.- When calling
backChecking before use can avoid undefined behavior.
Example 4: Use back to implement a stack
back is often used to implement the stack data structure (together with push_back and pop_back).
Example
#include
#include
class
Stack
{
private
:
std
::
vector
<
int
data;
public
:
// Push
void
push
(
int
value
)
{
data.
push_back
(
value
)
;
}
// Pop
void
pop
(
)
{
if
(
!
data.
empty
(
)
)
{
data.
pop_back
(
)
;
}
}
// Get the top element of the stack
int
top
(
)
{
if
(
!
data.
empty
(
)
)
{
return
data.
back
(
)
;
}
return
0
;
// Indicates the stack is empty
}
// Check whether the stack is empty
bool
empty
(
)
{
return
data.
empty
(
)
;
}
// Get the size of the stack
size_t
size
(
)
{
return
data.
size
(
)
;
}
}
;
int
main
(
)
{
Stack s
;
// Push operation
s.
push
(
10
)
;
s.
push
(
20
)
;
s.
push
(
30
)
;
std
::
cout
<<
"Stack size: "
<<
s.
size
(
)
<<
std
::
endl
;
std
::
cout
<<
"Top element (back): "
<<
s.
top
(
)
<<
std
::
endl
;
// Pop operation
s.
pop
(
)
;
std
::
cout
<<
"After popping, top element: "
<<
s.
top
(
)
<<
std
::
endl
;
s.
pop
(
)
;
std
::
cout
<<
"After another pop, top element: "
<<
s.
top
(
)
<<
std
::
endl
;
s.
pop
(
)
;
std
::
cout
<<
"After another pop, is the stack empty: "
<<
(
s.
empty
(
)
?
"Yes"
:
"No"
)
<<
std
::
endl
;
return
0
;
}
Expected output:
栈的大小: 3
栈顶元素 (back): 30
出栈后,栈顶元素: 20
再出栈后,栈顶元素: 10
再出栈后,栈是否为空: 是
Code analysis:
back()is used to get the top element of the stack (the last pushed element).- A stack is a Last In First Out (LIFO) data structure;
back()corresponds exactly to the top of the stack.
Example 5: Dynamically get the maximum value
Use back together with sort to get the maximum element after sorting.
Example
#include
#include
#include
#include
#include
int
main
(
)
{
std
::
srand
(
std
::
time
(
nullptr
)
)
;
std
::
vector
<
int
numbers;
// Randomly generate 5 numbers
for
(
int
i
=
0
;
i
<
5
;
++
i
)
{
numbers.
push_back
(
std
::
rand
(
)
%
100
)
;
}
std
::
cout
<<
"Original data: "
;
for
(
int
n
:
numbers
)
{
std
::
cout
<<
n
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
// Sort
std
::
sort
(
numbers.
begin
(
)
, numbers.
end
(
)
)
;
std
::
cout
<<
"After sorting: "
;
for
(
int
n
:
numbers
)
{
std
::
cout
<<
n
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
std
::
cout
<<
"Minimum (front): "
<<
numbers.
front
(
)
<<
std
::
endl
;
std
::
cout
<<
"Maximum (back): "
<<
numbers.
back
(
)
<<
std
::
endl
;
return
0
;
}
Code analysis:
- After sorting,
front()returns the minimum value,back()returns the maximum value. - which is a simple way to get the max/min values.
The C++ container class