List STL
List STL
•
Lists are sequence containers that allow non-contiguous memory allocation.
As compared to the vector, the list has slow traversal, but once a position
has been found, insertion and deletion are quick (constant time). Normally,
when we say a List, we talk about a doubly linked list. For implementing a
singly linked list, we use a forward_list.
std::list is the class of the List container. It is the part of C++ Standard Tem-
plate Library (STL) and is defined inside <list> header file.
Syntax:
std::list <data-type> name_of_list;
Example:
// C++ program to demonstrate the use of list containers
#include <iostream>
#include <list>
using namespace std;
int main()
{
// defining list
list<int> gqlist{12,45,8,6};
Output
12 45 8 6
In the above example, we created a std::list object named gqlist and initial-
ized it using an initializer_list. We can initialize the std::list objects using
many different ways mentioned here.
return 0;
}
return 0;
}
Output
List 1 (gqlist1) is : 0 2 4 6 8 10 12 14 16 18
List 2 (gqlist2) is : 27 24 21 18 15 12 9 6 3 0
gqlist1.front() : 0
gqlist1.back() : 18
gqlist1.pop_front() : 2 4 6 8 10 12 14 16 18
gqlist2.pop_back() : 27 24 21 18 15 12 9 6 3
gqlist1.reverse() : 18 16 14 12 10 8 6 4 2
gqlist2.sort(): 3 6 9 12 15 18 21 24 27
The above example only demonstrates the general usage of the std::list and
its member functions. The below table provides all the member functions of
std::list class and links to their detailed explanation.
pop_front() Removes the first element of the list, and reduces the
size of the list by 1.
list crbegin() and crend() crbegin() returns a constant reverse iterator which
points to the last element of the list i.e reversed be-
ginning of the container. crend() returns a constant re-
verse iterator which points to the theoretical element
preceding the first element in the list i.e. the reverse
end of the list.
Used to remove all the values from the list that corre-
list::remove_if() spond true to the predicate or condition given as a pa-
rameter to the function.