To get the last element in a C++ list using std::list, you can use the `back()` method.
In this example,
header for using std::list in C++.numbers
with integer elements.back()
method to get the last element.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {10, 20, 30, 40, 50};
int last_element = numbers.back();
std::cout << "Last element is: " << last_element << std::endl;
return 0;
}
Last element is: 50
In this example,
header for using std::list in C++.names
with string elements.back()
method to get the last element.#include <iostream>
#include <list>
#include <string>
int main() {
std::list<std::string> names = {"Alice", "Bob", "Charlie", "David"};
std::string last_element = names.back();
std::cout << "Last element is: " << last_element << std::endl;
return 0;
}
Last element is: David
In this tutorial, we learned How to get Last Element in a List in C++ language with well detailed examples.