C++ <list> push_front function

C++ container class <list>


push_frontis used in list toadd an element at the head of the linked listThe function is one of the signature operations of a linked list.

push_frontis a member function used tolinked list (list)ofheaderadd a new element.

Unlike vector,listThe time complexity of inserting an element at the head is O(1), which is very efficient.

Word Definitions: pushis pushing,frontIt means "front"; combined together, it means "push to the front," which is very vivid.


Basic syntax and parameters

push_frontIt is a member function of the container class, and calling it requires no arguments.

Syntax format

void push_front(const T& value);
void push_front(T&& value);  // C++11 之后(支持右值)

Parameter description

  • Parameter: value
    • Type: same as the element type specified when the container is defined.
    • Description: the value you want to add to the head of the container.

Function description

  • Return Value: void(no return value).
  • Effect: of the containersize()It will increase by 1. The new element becomes the first element of the linked list.

Example

Let's thoroughly master it through examples.push_frontUsage.

Example 1: Basic usage - adding an element at the head.

Example

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = {20, 30, 40};

    std::cout << "original list: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    // Add an element at the front
    numbers.push_front(10);

    std::cout << After push_front(10):;
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

Expected output:

原始 list: 20 30 40
push_front(10) 后: 10 20 30 40

Code analysis:

  • push_front(10)Add 10 to the head of the linked list, making it the first element.
  • Example 2: Building a linked list

    Usagepush_frontIt is convenient to build a linked list from the head.

    Example

    #include <iostream>
    #include <list>

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

        // Add to the head sequentially; the final order is opposite to the insertion order.
        data.push_front(5);
        data.push_front(4);
        data.push_front(3);
        data.push_front(2);
        data.push_front(1);

        std::cout << Constructed linked list:;
        for(int n : data) std::cout << n << " ";
        std::cout << std::endl;

        return 0;
    }

    Expected output:

    构建的链表: 1 2 3 4 5
    

    Code analysis:

    • Each timepush_frontBoth add new elements to the head.
    • The final linked list order is 1 -> 2 -> 3 -> 4 -> 5.

    C++ container class <list>

    other extensions