<list>
The <list>
header provides the std::list
container, which is a doubly-linked list implementation. It allows for constant time insertion and removal of elements from anywhere in the container, as well as bidirectional iteration.
std::list<T>
: The main container class, where T is the element type#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
numbers.push_front(0); // Add to the beginning
numbers.push_back(6); // Add to the end
std::cout << "Size: " << numbers.size() << std::endl;
// Iterating
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
// Accessing front and back
std::cout << "Front: " << numbers.front() << std::endl;
std::cout << "Back: " << numbers.back() << std::endl;
return 0;
}
std::list
#include <iostream>
#include <list>
void printList(const std::list<int>& lst) {
for (int num : lst) {
std::cout << num << " ";
}
std::cout << std::endl;
}
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
// Insert before 3
auto it = std::find(numbers.begin(), numbers.end(), 3);
if (it != numbers.end()) {
numbers.insert(it, 10);
}
std::cout << "After insertion: ";
printList(numbers);
// Remove all even numbers
numbers.remove_if([](int n) { return n % 2 == 0; });
std::cout << "After removing even numbers: ";
printList(numbers);
return 0;
}
remove_if
member function for conditional removalremove_if
#include <iostream>
#include <list>
void printList(const std::list<int>& lst) {
for (int num : lst) {
std::cout << num << " ";
}
std::cout << std::endl;
}
int main() {
std::list<int> list1 = {1, 3, 5};
std::list<int> list2 = {2, 4, 6};
// Splice entire list2 into list1 after the first element
auto it = std::next(list1.begin());
list1.splice(it, list2);
std::cout << "After splicing: ";
printList(list1);
// Create two new sorted lists
std::list<int> sorted1 = {1, 3, 5, 7};
std::list<int> sorted2 = {2, 4, 6, 8};
// Merge sorted lists
sorted1.merge(sorted2);
std::cout << "After merging: ";
printList(sorted1);
return 0;
}
splice
operation to insert elements from one list into anothermerge
operation to combine two sorted listsstd::list
is a container that implements a doubly-linked list, offering efficient insertion and removal of elements at any position. It's particularly useful in scenarios where elements need to be frequently inserted or removed from arbitrary positions in the container.
By using std::list
, C++ developers can manage collections of elements that require frequent insertions or deletions at arbitrary positions. However, it's important to consider the trade-offs, such as increased memory usage and lack of random access, when choosing between list
and other containers like vector
.