C++ list

In C++, a list is a container in the Standard Template Library (STL) that implements a doubly linked list. It provides efficient insertion and deletion of elements at both the beginning and the end of the list.

Advantages of list

1. Efficient Insertions/Deletions: Inserting and removing elements at any position in the list (especially at the front or back) is fast, with O(1) time complexity.

2. No Reallocation: Unlike vector, list does not need to reallocate memory when elements are added, making it more efficient for certain use cases.

Disadvantages of list

1. No Random Access: You cannot directly access elements using an index, unlike vectors or arrays. You need to traverse the list with iterators.

2. More Memory Usage: Each element in a list requires additional memory for storing the pointers to the next and previous elements.

Add element into list


#include <iostream>
#include <list>
using namespace std;

int main() {
    // Creating a list of integers
    list numbers;

    // Adding elements to the list
    numbers.push_back(20);  // Add 20 at the end
    numbers.push_back(30);  // Add 30 at the end
    numbers.push_front(10);  // Add 10 at the beginning
    numbers.push_back(40);  // Add 40 at the end

    // Iterating through the list using a range-based for loop
    std::cout << "Elements in the list: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << std::endl;

    return 0;
}

Output:

Elements in the list: 10 20 30 40

Access the elements from the list


#include <iostream>
#include <list>
using namespace std;

int main() {
    // Creating a list of integers
    list numbers = {10, 20, 30, 40, 50};

  // Accessing the front and back elements
    std::cout << "First element: " << numbers.front() << std::endl;
    std::cout << "Last element: " << numbers.back() << std::endl;

    
    // Iterating through the list using a range-based for loop
    std::cout << "Elements in the list: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << std::endl;

    return 0;
}

Output:

First element: 10
Last element: 50
Elements in the list: 10 20 30 40 50

Remove element from elements


#include <iostream>
#include <list>
using namespace std;

int main() {
    // Creating a list of integers
    list numbers = {10, 20, 30, 40, 50};

    // Removing elements
    numbers.pop_front();  // Remove the first element (10)
    numbers.pop_back();   // Remove the last element (50)

    // Iterating after removal
    cout << "Elements after pop operations: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}
Elements after pop operations: 20 30 40