List
Anonymous contributor
Published Oct 31, 2024
Contribute to Docs
List in C++ is a sequential container and part of the Standard Template Library (STL) that stores elements in non-contiguous memory locations. It is implemented as a doubly linked list, allowing efficient insertion and deletion of elements at any known position with average constant time complexity.
Syntax
#include <list>
std::list<data-type> name_of_list;
data-type
: Specifies the type of elements stored in the list, which can be any valid C++ type (e.g.,int
,double
, or user-defined types).name_of_list
: The variable name for the list instance, used to reference and manipulate the list within the code.
Example
#include <iostream>#include <list>int main() {// Declare a list of integersstd::list <int> myList;// Adding elements to the listmyList.push_back(10);myList.push_back(20);myList.push_front(5);// Displaying elements in the liststd::cout << "List elements: ";for (const auto & value: myList) {std::cout << value << " ";}std::cout << std::endl;// Removing an elementmyList.remove(10);// Displaying the updated liststd::cout << "Updated list elements after deletion: ";for (const auto & value: myList) {std::cout << value << " ";}std::cout << std::endl;return 0;}
The output for the above code is:
List elements: 5 10 20Updated list elements after deletion: 5 20
Codebyte Example
Run the following codebyte example to understand how List works in C++:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.