The back() Method is used to get the last element from the List.
Let us say, we have a List that contains three names, Mohan, Kriti and Salim. And we want to get the last element i.e. Salim from the List.
We can use the back() Method to achieve the above.
#include <iostream> #include <list> using namespace std; int main() { list<string> x = {"Mohan", "Kriti", "Salim"}; string element = x.back(); cout << element << endl; return 0; }
So, in the above code we have created a List and initialised to the variable x.
list<string> x = {"Mohan", "Kriti", "Salim"};
Below is how the values are positioned in the List,
Next, we have used the back() method to get the last element from the List and store it in a variable element.
string element = x.back();
And when we print the value of element variable, we get Salim as output.