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::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 function used
size()

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.

Example
std::list myList = {1, 2, 3, 4, 5};
int size = myList.size(); // size is 5
empty()

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.

Example
std::list myList;
bool isEmpty = myList.empty(); // isEmpty is true
clear()

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.

Example
std::list myList = {1, 2, 3, 4, 5};
myList.clear(); // The list is now empty
sort()

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.

Example
std::list myList = {5, 2, 1, 4, 3};
myList.sort(); // The list is now {1, 2, 3, 4, 5}
reverse()

This member function reverses the order of elements in the list. It swaps the positions of the elements, effectively reversing the sequence.

Example
std::list myList = {1, 2, 3, 4, 5};
myList.reverse(); // The list is now {5, 4, 3, 2, 1}