C++ std::list::back
The std::list::back
function provides access to the last element of a std::list
. This function returns a reference to the last element, allowing it to be read or modified.
Syntax of std::list::back
reference back();
const_reference back() const;
Parameters
The std::list::back
function does not take any parameters.
Return Value
Returns a reference to the last element in the list. If the list is const
, the returned reference is also const
, meaning the element cannot be modified.
Exceptions
The std::list::back
function does not throw exceptions. However, calling this function on an empty list results in undefined behavior. It is recommended to check whether the list is empty using empty()
before calling this function.
Examples for std::list::back
Example 1: Accessing the Last Element Using std::list::back
This example demonstrates how to use back()
to access the last element of a list:
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {10, 20, 30};
std::cout << "The last element is: " << myList.back() << std::endl;
return 0;
}
Explanation:
- Define a list: A
std::list
namedmyList
is initialized with elements{10, 20, 30}
. - Access the last element: The
back()
function is called onmyList
to retrieve the last element, which is30
. - Print the element: The retrieved element is printed to the console.
Output:
The last element is: 30
Example 2: Modifying the Last Element Using std::list::back
This example demonstrates how to modify the last element of a list using back()
:
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {1, 2, 3};
std::cout << "Before modification, last element: " << myList.back() << std::endl;
myList.back() = 100; // Modify the last element
std::cout << "After modification, last element: " << myList.back() << std::endl;
return 0;
}
Explanation:
- Define a list: A
std::list
namedmyList
is initialized with elements{1, 2, 3}
. - Access the last element: The
back()
function is called to retrieve the last element, which is3
. - Modify the last element: The value of the last element is updated to
100
usingmyList.back() = 100
. - Print the modified element: The updated last element is printed to the console.
Output:
Before modification, last element: 3
After modification, last element: 100
Exception Handling in std::list::back
The std::list::back
function does not throw exceptions. However, calling this function on an empty list results in undefined behavior. It is recommended to use the empty()
function to check whether the list is empty before calling back()
.
Example 3: Avoiding Undefined Behavior with std::list::back
#include <iostream>
#include <list>
int main() {
std::list<int> emptyList;
if (!emptyList.empty()) {
std::cout << "Last element: " << emptyList.back() << std::endl;
} else {
std::cout << "The list is empty. No elements to access." << std::endl;
}
return 0;
}
Output:
The list is empty. No elements to access.