C++ <list> pop_front function

C++ container class <list>


pop_frontis used in the list toremove the head element of the linked listThe function is one of the characteristic operations of a linked list.

pop_frontIt is a member function of the container class, used to delete the first element of a linked list.

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

Word Definitions: popis to pop,frontmeans "front"; together, it means popping the front element.


Basic syntax and parameters

pop_frontIt is a member function of the container class; calling it requires no parameters.

Syntax format

void pop_front();

Parameter description

  • Parameter: No parameters

Function description

  • Return Value: void(No return value).
  • Effect: of the containersize()will decrease by 1. The first element is deleted.
  • Note: if the linked list is empty, callpop_frontis undefined behavior.

Example

Example 1: Basic usage - deleting the head element

Example

#include <iostream>
#include <list>

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

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

    // Delete the head element
    numbers.pop_front();
    std::cout << "after pop_front(): ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    numbers.pop_front();
    std::cout << "after pop_front() again: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

Expected output:

原始 list: 10 20 30 40 50
pop_front() 后: 20 30 40 50
再 pop_front() 后: 30 40 50

Example 2: Implementing a queue

Usagepush_backandpop_frontCan implement a queue.

Example

#include <iostream>
#include <list>
#include <string>

class Queue {
private:
    std::list<std::string> data;

public:
    void enqueue(const std::string& item) {
        data.push_back(item);
    }

    void dequeue() {
        if(!data.empty()) {
            data.pop_front();
        }
    }

    std::string front() const {
        return data.front();
    }

    bool empty() const {
        return data.empty();
    }

    size_t size() const {
        return data.size();
    }
};

int main() {
    Queue q;

    q.enqueue("User A");
    q.enqueue("User B");
    q.enqueue("User C");

    std::cout << "Queue size: " << q.size() << std::endl;

    while(!q.empty()) {
        std::cout << "Processing: " << q.front() << std::endl;
        q.dequeue();
    }

    return 0;
}

Expected output:

队列大小: 3
处理: 用户A
处理: 用户B
处理: 用户C

C++ container class <list>

other extensions