C++ list
π C++ list (Doubly Linked List)
std::list is a doubly linked list container in the C++ STL.
It allows fast insertion and deletion anywhere in the list, but does not support random access.
πΉ 1. Why Use list?
Fast insert/delete in the middle (O(1) with iterator)
No reallocation or shifting of elements
Stable iterators (remain valid after insert/erase elsewhere)
β Not good for:
Index-based access
Cache-friendly traversal
Sorting with random access
πΉ 2. Include Header
πΉ 3. Declaring a List
With size/value:
πΉ 4. Adding Elements
πΉ 5. Accessing Elements
list has no [] or at().
πΉ 6. Traversing a List
Range-based loop
Iterator
πΉ 7. Removing Elements
Remove by value:
Remove with condition:
πΉ 8. Insert & Erase Using Iterator
πΉ 9. Size & State
πΉ 10. Sorting a List
std::sort β does NOT work with list.
β Use built-in list::sort():
πΉ 11. Reversing a List
πΉ 12. Merging Two Sorted Lists
πΉ 13. list vs vector
| Feature | list | vector |
|---|---|---|
| Memory | Non-contiguous | Contiguous |
| Access | No random access | O(1) random |
| Insert/Delete (middle) | O(1) | O(n) |
| Cache friendly | β | β |
| Iterators | Stable | May invalidate |
πΉ 14. Time Complexity
| Operation | Complexity |
|---|---|
| Insert/Delete (with iterator) | O(1) |
| Search | O(n) |
| Access first/last | O(1) |
| Sort | O(n log n) |
β Common Mistakes
π Summary
std::list= doubly linked listFast insert/delete anywhere
No random access
Use
list::sort()andlist::reverse()Best when frequent middle operations are needed
