Standard Template Library
Published by
sanya sanya
The C++ Standard Template Library (STL) provides the ‘list’ container, which is a doubly-linked list implementation.
It offers several member functions to manipulate and access elements in the list.
1. Creating a list: Used to create an empty list.
Code:
#include
#include
using namespace std;
int main() {
list
return 0;
}
2. Inserting elements: Elements can be inserted at the front, back or any specific position.
Code:
list
myList.push_back(10); // Insert an element at the back
myList.push_front(20); // Insert an element at the front
myList.insert(next(myList.begin()), 30); // Insert an element at a specific position
3. Accessing elements: This method helps in accessing the first or the last element.
Code:
list
cout << myList.front() << endl; // Access the first element
cout << myList.back() << endl; // Access the last element
4. Iterating over the list: Iteration over the list is also possible using STL.
Code:
list
// Using a for loop
for (const auto& element : myList) {
cout << element << " ";
}
cout << endl;
// Using iterators
for (auto it = myList.begin(); it != myList.end(); ++it) {
cout << *it << " ";
}
cout << endl;
5. Removing elements: Elements can be popped or removed form the front, back or any specific position in the list.
Code:
list
myList.pop_front(); // Remove the first element
myList.pop_back(); // Remove the last element
myList.erase(next(myList.begin())); // Remove an element at a specific position
myList.remove(20); // Remove all elements with the value 20
6. Getting the size and checking emptiness:
Code:
list
cout << "Size: " << myList.size() << endl; // Get the size of the list
cout << "Empty: " << (myList.empty() ? "Yes" : "No") << endl; // Check if the list is empty
7. Sorting the list:
Code:
list
myList.sort(); // Sort the elements in ascending order
// Custom sorting order
myList.sort([](int a, int b) { return a > b; }); // Sort in descending order
Library
WEB DEVELOPMENT
FAANG QUESTIONS