C++ Library — <list>
List is a popularly used sequence container. Container is an object that holds data of same type. List container is implemented as doubly linked-list, hence it provides bidirectional sequential access to it’s data.
List doesn’t provide fast random access, it only supports sequential access in both directions. List allows insertion and deletion operation anywhere within a sequence in constant time.
Elements of list can be scattered in different chunks of memory. Container stores necessary information to allow sequential access to it’s data. Lists can shrink or expand as needed from both ends at run time. The storage requirement is fulfilled automatically by internal allocator.
Zero sized lists are also valid. In that case list.begin() and list.end() points to same location. But behavior of calling front() or back() is undefined.
Definition
Below is definition of std::list from <list> header file
Parameters
T − Type of the element contained.
T may be substituted by any other data type including user-defined type.
Alloc − Type of allocator object.
By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent.
Member types
Following member types can be used as parameters or return type by member functions.
| Sr.No. | Member types | Definition |
|---|---|---|
| 1 | value_type | T (First parameter of the template) |
| 2 | allocator_type | Alloc (Second parameter of the template) |
| 3 | reference | value_type& |
| 4 | const_reference | const value_type& |
| 5 | pointer | value_type* |
| 6 | const_pointer | const value_type* |
| 7 | iterator | a random access iterator to value_type |
| 8 | const_iterator | a random access iterator to const value_type |
| 9 | reverse_iterator | std::reverse_iterator <iterator> |
| 10 | const_reverse_iterator | std::reverse_iterator <const_iterator> |
| 11 | size_type | size_t |
| 12 | difference_type | ptrdiff_t |
Functions from <list>
Below is list of all methods from <list> header.
Constructors
| Sr.No. | Method & Description |
|---|---|
| 1 | list::list default constructor |
Constructs an empty list with zero elements.
Constructs a new list with n elements and assigns val to each element of list.
Constructs a new list with n elements and assign zero value to each element of list.
Constructs a list with as many elements as in range of first to last.
Constructs a list with copy of each elements present in existing list.
Constructs a list with the contents of other using move semantics.
Constructs a list with the contents of other using move semantics.
Destructor
| Sr.No. | Method & Description |
|---|---|
| 1 | list:: |
Destroys list object by deallocating it’s memory.
Member functions
| Sr.No. | Method & Description |
|---|---|
| 1 | list::assign range version |
Assigns new value to list by replacing old ones.
Assigns new values to list by replacing old ones.
Assigns new values to list by replacing old ones.
Returns a reference to the last element of the list.
Returns a random access iterator which points to the first element of the list.
Returns a constant random access iterator which points to the beginning of the list.
Returns a constant random access iterator which points to the end of the list.
Destroys the list by removing all elements from the list and sets size of list to zero.
Returns a constant reverse iterator which points to the last element of the list.
Returns a constant reverse iterator which points to the theoretical element preceding the first element in the list.
Extends list by inserting new element at a given position.
Inserts new element at the end of list and increases size of list by one.
Inserts new element at the beginning of the list and increases size of list by one.
Tests whether list is empty or not.
Returns a random access iterator which points to the last element of the list.
Removes single element from the the list.
Removes range of element from the the list.
Returns a reference to the first element of the list.
Returns an allocator associated with list
Extends iterator by inserting new element at position in list.
Extends list by inserting new elements in the container.
Extends list by inserting new elements in the container.
Extends list by inserting new element in the container.
Extends list by inserting new elements in the container
Returns the maximum number of elements can be held by list.
Merges two sorted lists into one.
Merges two sorted lists into one.
Merges two sorted lists into one by using move semantics.
Merges two sorted lists into one by using move semantics.
Assigns new contents to the list by replacing old ones.
Assign new contents to the list by replacing old ones.
Assign new contents to the list by replacing old ones.
Removes last element from list.
Removes first element from list.
Inserts new element at the end of list.
Inserts new element at the end of list.
Inserts new element at the beginning of list.
Inserts new element at the beginning of list.
Returns a reverse iterator which points to the last element of the list.
removes element(s) from the list that matches the value.
removes elements from the list that fulfills the condition.
Returns a reverse iterator which points to the reverse end of the list.
Changes the size of list.
Changes the size of list.
Reverses the order of the elements present in the list.
Returns the number of elements present in the list.
Sorts the elements of the list.
Sorts the elements of the list.
Transfers all elements from list to *this.
Transfers a element pointed to by iterator i from list x into *this.
Transfers all elements from list x to *this by using move semantics.
Transfers the elements in the range of first to last from x to *this.
Transfers the element pointed to by iterator i from list x into *this by using move semantics.
Transfers the elements in the range of first to last from x to *this by using move semantics.
Как использовать библиотеку list в с
Контейнер list представляет двухсвязный список. Для его использования необходимо подключить заголовочный файл list .
Получение элементов
В отличие от других контейнеров для типа list не определена операция обращения по индексу или функция at(), которая выполняет похожую задачу.
Тем не менее для контейнера list можно использовать функции front() и back() , которые возвращают соответственно первый и последний элементы.
Чтобы обратиться к элементам, которые находятся в середине (после первого и до последнего элементов), придется выполнять перебор элементов с помощью циклов или итераторов:
Размер списка
Для получения размера списка можно использовать функцию size() :
Функция empty() позволяет узнать, пуст ли список. Если он пуст, то функция возвращает значение true, иначе возвращается значение false:
С помощью функции resize() можно изменить размер списка. Эта функция имеет две формы:
resize(n) : оставляет в списке n первых элементов. Если список содержит больше элементов, то он усекается до первых n элементов. Если размер списка меньше n, то добавляются недостающие элементы и инициализируются значением по умолчанию
resize(n, value) : также оставляет в списке n первых элементов. Если размер списка меньше n, то добавляются недостающие элементы со значением value
Изменение элементов списка
Функция assign() позволяет заменить все элементы списка определенным набором. Она имеет следующие формы:
assign(il) : заменяет содержимое контейнера элементами из списка инициализации il
assign(n, value) : заменяет содержимое контейнера n элементами, которые имеют значение value
assign(begin, end) : заменяет содержимое контейнера элементами из диапазона, на начало и конец которого указывают итераторы begin и end
Функция swap() обменивает значениями два списка:
Добавление элементов
Для добавления элементов в контейнер list применяется ряд функций.
push_back(val) : добавляет значение val в конец списка
push_front(val) : добавляет значение val в начало списка
emplace_back(val) : добавляет значение val в конец списка
emplace_front(val) : добавляет значение val в начало списка
emplace(pos, val) : вставляет элемент val на позицию, на которую указывает итератор pos. Возвращает итератор на добавленный элемент
insert(pos, val) : вставляет элемент val на позицию, на которую указывает итератор pos, аналогично функции emplace. Возвращает итератор на добавленный элемент
insert(pos, n, val) : вставляет n элементов val начиная с позиции, на которую указывает итератор pos. Возвращает итератор на первый добавленный элемент. Если n = 0, то возвращается итератор pos.
insert(pos, begin, end) : вставляет начиная с позиции, на которую указывает итератор pos, элементы из другого контейнера из диапазона между итераторами begin и end. Возвращает итератор на первый добавленный элемент. Если между итераторами begin и end нет элементов, то возвращается итератор pos.
insert(pos, values) : вставляет список значений values начиная с позиции, на которую указывает итератор pos. Возвращает итератор на первый добавленный элемент. Если values не содержит элементов, то возвращается итератор pos.
Функции push_back() , push_front() , emplace_back() и emplace_front() :
Добавление в середину списка с помощью функции emplace() :
Добавление в середину списка с помощью функции insert() :
Удаление элементов
Для удаления элементов из контейнера list могут применяться следующие функции:
clear(p) : удаляет все элементы
pop_back() : удаляет последний элемент
pop_front() : удаляет первый элемент
erase(p) : удаляет элемент, на который указывает итератор p. Возвращает итератор на элемент, следующий после удаленного, или на конец контейнера, если удален последний элемент
erase(begin, end) : удаляет элементы из диапазона, на начало и конец которого указывают итераторы begin и end. Возвращает итератор на элемент, следующий после последнего удаленного, или на конец контейнера, если удален последний элемент
Использовать контейнер списка STL в C++ STL

В этой статье будет продемонстрировано несколько методов использования контейнера список STL в C++.
Please enable JavaScript
Используйте std::list<T> для объявления объекта-контейнера списка в C++
Контейнер std::list является частью стандартной библиотеки шаблонов и реализует структуру данных списка, которая обеспечивает постоянную вставки/удаление элементов из любой позиции. Обычно он реализуется как двусвязный список и поддерживает двунаправленную итерацию в отличие от std::forward_list . С другой стороны, std::list не поддерживает быстрый произвольный доступ к таким элементам, как std::vector или std::deque . Он предоставляет только две функции с постоянным временем, front и back для доступа к первому и последнему элементам. std::list можно инициализировать с заданным типом данных и общей нотацией списка инициализаторов, как показано в следующем примере кода. Методы push_back и push_front можно использовать для добавления элементов к любой стороне списка.
Используйте функцию insert() для вставки элементов в указанное место в списке в C++
Функция-член insert() может использоваться для добавления элементов в заданную позицию. Функция имеет несколько перегрузок, первая из которых принимает всего два аргумента: итератор и ссылку на объект. Данный элемент вставляется перед элементом, на который указывает итератор. В следующем фрагменте кода показано, как найти конкретное значение в списке и затем вставить перед ним нужный элемент.
Используйте функцию swap() , чтобы поменять местами элементы двух списков в C++
Еще одна полезная функция-член контейнера std::list — это swap() , которая обменивает элементы объекта списка с другим списком, который передается в качестве единственного аргумента. Обратите внимание, что эта операция не перемещает и не копирует отдельные элементы, и все итераторы/ссылки остаются действительными после вызова функции.
Используйте функцию merge() , чтобы объединить два отсортированных списка в один
Как вариант, можно объединить элементы двух отсортированных списков в один с помощью функции-члена merge . Обратите внимание, что оба списка должны быть отсортированы в порядке возрастания. merge принимает ссылку на объект списка, элементы которого объединяются с вызывающим объектом. После операции объект списка, переданный в качестве аргумента, становится пустым. Функция упорядочивает элементы результирующего объекта списка в возрастающем порядке, как показано в следующем примере кода.
std::list in C++ with Example
In C++, the std::list refers to a storage container. The std:list allows you to insert and remove items from anywhere. The std::list is implemented as a doubly-linked list. This means list data can be accessed bi-directionally and sequentially.
The Standard Template Library list doesn’t support fast random access, but it supports sequential access from all directions.
You can scatter list elements in different memory chunks. The information needed for sequential access to data is stored in a container. The std::list can expand and shrink from both ends as needed during runtime. An internal allocator automatically fulfills the storage requirements.
In this C++ tutorial, you will learn:
Why use std::list?
Here, are reason of using std::List :
- The std::list does better compare to other sequence containers like array and vector.
- They have a better performance in inserting, moving, and extracting elements from any position.
- The std::list also does better with algorithms that perform such operations intensively.
List Syntax
To define the std::list, we have to import the <list> header file. Here is the std::list definition syntax:
Here is a description of the above parameters:
- T – Defines the type of element contained.You can substitute T by any data type, even user-defined types.
- Alloc – Defines the type of the allocator object.This uses the allocator class template by default. It’s value-dependent and uses a simple memory allocation model.
Examples 1:
Output:

Here is a screenshot of the code:

Code Explanation:
- Include the algorithm header file to use its functions.
- Include the iostream header file to use its functions.
- Include the list header file to use its functions.
- Call the main() function. The program logic should be added within the body of this function.
- Create a list named my_list with a set of 4 integers.
- Use a for loop to create a loop variable x. This variable will be used to iterate over the list elements.
- Print out the values of the list on the console.
- End of the body of the for a loop.
- End of the body of the main() function.
C++ List Functions
Here are the common std::list functions:
| Function | Description |
| insert() | This function inserts a new item before the position the iterator points. |
| push_back() | This functions add a new item at the list’s end. |
| push_front() | It adds a new item at the list’s front. |
| pop_front() | It deletes the list’s first item. |
| size() | This function determines the number of list elements. |
| front() | To determines the list’s first items. |
| back() | To determines the list’s last item. |
| reverse() | It reverses the list items. |
| merge() | It merges two sorted lists. |
<list> Constructors
Here is the list of functions provided by the <list> header file:
- Default constructor std::list::list()- It creates an empty list, that, with zero elements.
- Fill constructor std::list::list()- It creates a list with n elements and assigns a value of zero (0) to each element.
- Range constructor std::list::list()- creates a list with many elements in the range of first to last.
- Copy constructor std::list::list()- It creates a list with a copy of each element contained in the existing list.
- Move constructor std::list::list()- creates a list with the elements of another list using move semantics.
- Initializer list constructor std::list::list()-It creates a list with the elements of another list using move semantics.
Example 2:
Output:

Here is a screenshot of the code:

Code Explanation:
- Include the iostream header file to use its functions.
- Include the list header file to use its functions.
- Include the std namespace in the code to use its classes without calling it.
- Call the main() function. The program logic should be added within the body of this function.
- Create an empty list named l.
- Create a list named l1 with a set of 3 integers.
- Create a list named l2 with all elements in the list named l1, from the beginning to the end.
- Create a list named l3 using move semantics. The list l3 will have same contents as the list l2.
- Print the size of the list named l on the console alongside other text.
- Print some text on the console.
- Create an iterator named it and use it to iterate over the elements of the list named l2.
- Print the elements of the list named l2 on the console.
- Print some text on the console.
- Create an iterator named it and use it to iterate over the elements of the list named l3.
- Print the elements of the list named l3 on the console.
- The program must return value upon successful completion.
- End of the body of the main() function.
Container properties
Here is the list of container properties:
| Property | Description |
| Sequence | Sequence containers order their elements in a strict linear sequence. Elements are accessed by their position in the sequence. |
| Doubly-linked list | Every element has information on how to locate previous and next elements. This allows for constant time for insertion and deletion operations. |
| Allocator-aware | An allocator object is used for modifying the storage size dynamically. |
Inserting into a List
There are different functions that we can use to insert values into a list. Let’s demonstrate this:
Example 3:
Output:

Here is a screenshot of the code:

Code Explanation:
- Include the algorithm header file to use its functions.
- Include the iostream header file to use its functions.
- Include the list header file to use its functions.
- Call the main() function. The program logic should be added within the body of this function.
- Create a list named my_list with a set of 4 integers.
- Insert the element 11 to the front of the list named my_list.
- Insert element 18 to the end of the list named my_list.
- Create an iterator it and using it to find the element 10 from the list my_list.
- Use an if statement to determine if the above element was found or not.
- Insert element 21 before the above element if it was found.
- End of the body of the if statement.
- Use a for loop to create a loop variable x. This variable will be used to iterate over the list elements.
- Print out the values of the list on the console.
- End of the body of the for a loop.
- End of the body of the main() function.
Deleting from a List
It’s possible to delete items from a list. The erase() function allows you to delete an item or a range of items from a list.