STL (Standard Template Library) list in C++. The list is a doubly-linked list implementation provided by the C++ STL that allows for efficient insertion and removal of elements at both ends and in the middle of the list.
#include<list>
std::list<DataType> myList;
Replace DataType with the actual data type you want to store in the list.
You can use the push_back and push_front member functions to add elements at the end and beginning of the list, respectively.
myList.push_back(element); // Insert element at the end myList.push_front(element); // Insert element at the beginning
The list doesn't provide random access, so you can't access elements using indexes. However, you can use iterators to traverse the list and access the elements.
// Using an iterator to access elements std::list::iterator it; for (it = myList.begin(); it != myList.end(); ++it) { // Access the element using the iterator: *it }
To remove elements, you can use the pop_back and pop_front member functions to remove the last and first elements, respectively. Alternatively, you can use the erase member function along with an iterator to remove a specific element.
myList.pop_back(); // Remove the last element myList.pop_front(); // Remove the first element std::list<DataType>::iterator it = myList.begin(); ++it; // Advance the iterator myList.erase(it); // Remove the element pointed by the iterator
This member function returns the number of elements in the list. It provides the current size of the list by counting the number of elements present.
std::listmyList = {1, 2, 3, 4, 5}; int size = myList.size(); // size is 5
This member function checks whether the list is empty or not. It returns true if the list is empty (contains no elements), and false otherwise.
std::listmyList; bool isEmpty = myList.empty(); // isEmpty is true
This member function removes all elements from the list, leaving it empty. It deallocates the memory occupied by the list elements, effectively clearing the list.
std::listmyList = {1, 2, 3, 4, 5}; myList.clear(); // The list is now empty
This member function sorts the elements in the list in ascending order. It rearranges the elements using a comparison operator (< by default) to determine the order.
std::listmyList = {5, 2, 1, 4, 3}; myList.sort(); // The list is now {1, 2, 3, 4, 5}
This member function reverses the order of elements in the list. It swaps the positions of the elements, effectively reversing the sequence.
std::listmyList = {1, 2, 3, 4, 5}; myList.reverse(); // The list is now {5, 4, 3, 2, 1}