List back() function in C++ STLWhat is C++ STL?STL stands for Standard Template Library in C++. This library contains inbuilt functions and classes for various uses. The list is also the data structure which is defined in the standard template library (STL). There are a lot of in-built functions used with the list data structure to insert the elements at starting, ending or at any specific position. Some functions are used to delete the elements from the list at the starting, ending or at any specific position. For example:
What is back() function?In the list, we have a back() function which returns the reference or pointer to the last element of the list. If we compare the end() function to back() function, the end() function returns the iterator to the last element, whereas this returns the pointer to the last element. Syntax: listName.back(); This function does not accept any argument or parameter. C++ Example 1:Output: Explanation In the above code, we declare a list of integers, and then we push the elements in the list using the push_back function. Since the last element of the list we pushed was ten, and when we use the back() function and print the element, it prints ten as the last element. C++ Example 2:Output: Explanation In the above code, we have a list of characters, and we have printed the last element and its ASCII value. C++ Example 3:When the list is empty: Output: Explanation In the above code, we declared the list of type integers, but we did not push any elements in the list. Now, if we use the back function to get the last element, it returns 0 as the last element, and if we print the size of the list, then it returns 0, which is correct. C++ Example 4:Output: Explanation In the above code, we have created the list of characters but did not push any element in the list. Since the list is empty and when we use the back() function to get the last element of the list, it returns an empty or null character. So, if the list is empty and if we use the back() function for the list, it shows some undefined behavior. |
Javatpoint provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India