STL List in C++

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.

Header file
#include<list>
Syntax of Declare a list
std::list<DataType> myList;

Replace DataType with the actual data type you want to store in the list.

Insert elements into 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
Accessing elements in the list

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<DataType>::iterator it;
for (it = myList.begin(); it != myList.end(); ++it) {
    // Access the element using the iterator: *it
}
Removing elements from the list

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
Some common functions used

List operations such as size(), empty(), clear(), sort(), and reverse() are covered.