In C++, the std::list container from the Standard Template Library (STL) allows you to store a sequence of elements. It is particularly useful when you want fast insertions and deletions from both the front and the back.
In this blog, we will understand what a list is, how to use it, and walk through some basic operations with simple examples.
✅ What is a list in C++?
A list is a doubly linked list that allows:
- Fast insertions and deletions from both the beginning and the end.
- Dynamic resizing as elements are added or removed.
- No random access using indexing (like you do with
vectoror arrays).
🔧 How to Use std::list in C++
1. Include the Header
#include <list>
2. Create and Initialize a List
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> marks = {10, 20, 30};
for (int mark : marks) {
cout << mark << endl;
}
return 0;
}
🔁 Common List Operations
🔹 push_back(val) – Add element at the end
marks.push_back(40); // {10, 20, 30, 40}
🔹 push_front(val) – Add element at the beginning
marks.push_front(5); // {5, 10, 20, 30, 40}
🔹 pop_back() – Remove the last element
marks.pop_back(); // Removes 40
🔹 pop_front() – Remove the first element
marks.pop_front(); // Removes 5
🔹 insert(pos, val) – Insert at a specific position
auto it = next(marks.begin(), 2); // 3rd position
marks.insert(it, 25); // {10, 20, 25, 30}
🔹 clear() – Remove all elements
marks.clear(); // List becomes empty
🔹 resize(n) – Resize the list
marks.resize(5); // Adds default 0s if increased
🔹 assign(n, val) – Assign n copies of a value
marks.assign(4, 100); // {100, 100, 100, 100}
🔹 remove(val) – Remove all occurrences of a value
marks.remove(100); // Removes all 100s
🔹 remove_if(condition) – Conditional removal
marks = {10, 20, 35, 40};
marks.remove_if([](int n) { return n > 30; }); // Removes 35 and 40
🔹 unique() – Remove consecutive duplicates
marks = {10, 10, 20, 20, 30};
marks.unique(); // Result: {10, 20, 30}
🔹 sort() – Sort in ascending order
marks = {30, 10, 20};
marks.sort(); // {10, 20, 30}
🔹 reverse() – Reverse the list
marks.reverse(); // {30, 20, 10}
🔹 merge(list2) – Merge another list (must be sorted)
list<int> list1 = {10, 30};
list<int> list2 = {20, 40};
list1.merge(list2); // list1 = {10, 20, 30, 40}, list2 becomes empty