Cover Image for list::push_front() and list::push_back() in C++ STL
136 views

list::push_front() and list::push_back() in C++ STL

The C++ STL std::list is a doubly-linked list container that provides efficient insertion and deletion of elements at both the front and back of the list. You can use list::push_front() to insert an element at the beginning of the list, and list::push_back() to insert an element at the end of the list.

Here’s how you can use push_front() and push_back() with std::list:

C++
#include <iostream>
#include <list>

int main() {
    std::list<int> myList;

    // Push elements to the front of the list using push_front()
    myList.push_front(1);
    myList.push_front(2);
    myList.push_front(3);

    // Push elements to the back of the list using push_back()
    myList.push_back(4);
    myList.push_back(5);
    myList.push_back(6);

    // Display the elements in the list
    for (const int& num : myList) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

In this example:

  • We create a std::list called myList.
  • We use push_front() to insert elements at the beginning of the list (3, 2, and 1) and push_back() to insert elements at the end of the list (4, 5, and 6).
  • Finally, we use a loop to iterate through the elements in the list and display them.

The output of this program will be:

Plaintext
3 2 1 4 5 6

Both push_front() and push_back() are efficient operations for std::list because it’s a doubly-linked list, and inserting elements at the beginning or end does not require shifting or moving other elements, unlike some other data structures like std::vector. This makes std::list a good choice when you need efficient insertion and removal of elements at both ends of the list.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS