STL Containers - List in C++
Introduction to List
The std::list
is a sequence container that allows non-contiguous memory allocation. As compared to vector
, which uses contiguous memory, list
allows for constant time insert and erase operations anywhere within the sequence. This makes it a suitable choice for applications where frequent insertions and deletions are required.
Creating a List
A list can be created by including the <list>
header and using the std::list
template. Here is an example:
#include <list>
int main() {
std::list<int> myList;
return 0;
}
Basic Operations on List
Let's explore some basic operations such as adding, removing, and iterating through elements in a list.
Adding Elements
Elements can be added to a list using functions like push_back
and push_front
:
#include <list>
int main() {
std::list<int> myList;
myList.push_back(10);
myList.push_front(20);
return 0;
}
Removing Elements
Elements can be removed using pop_back
and pop_front
:
#include <list>
int main() {
std::list<int> myList;
myList.push_back(10);
myList.push_back(20);
myList.pop_back();
myList.pop_front();
return 0;
}
Iterating Through a List
We can iterate through the elements of a list using iterators:
#include <list>
int main() {
std::list<int> myList = {10, 20, 30};
for (auto it = myList.begin(); it != myList.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
Advanced Operations on List
More advanced operations include sorting, reversing, and merging lists.
Sorting a List
The sort
function sorts the elements in ascending order:
#include <list>
int main() {
std::list<int> myList = {30, 10, 20};
myList.sort();
for (auto it = myList.begin(); it != myList.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
Reversing a List
The reverse
function reverses the order of elements:
#include <list>
int main() {
std::list<int> myList = {10, 20, 30};
myList.reverse();
for (auto it = myList.begin(); it != myList.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
Merging Lists
The merge
function merges two sorted lists into one:
#include <list>
int main() {
std::list<int> list1 = {1, 3, 5};
std::list<int> list2 = {2, 4, 6};
list1.merge(list2);
for (auto it = list1.begin(); it != list1.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
Conclusion
The std::list
container is a powerful tool in the C++ Standard Library, particularly when frequent insertions and deletions are required. Understanding how to effectively use its various functions can greatly enhance the performance and flexibility of your programs.