Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Standard Template Library

User image

Published by

sanya sanya

Published at: 3rd Aug, 2023
1.965 mins read

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 myList; // Creates an empty list of integers

return 0;

}

2. Inserting elements: Elements can be inserted at the front, back or any specific position.

Code:

list myList;

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 myList = {10, 20, 30};

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 myList = {10, 20, 30};

// 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 = {10, 20, 30};

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 myList = {10, 20, 30};

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 = {30, 10, 20};

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