C++ <list> pop_back function

C++ container class <list>


pop_backis used in list todelete the element at the end of the linked listof the function.

pop_backis a member function of the container class, used to delete the last element of the linked list.

In the list,pop_backhas a time complexity of O(1), very efficient.

Word Definitions: popis to pop,backmeans "back/behind", and together it means popping the back element.


Basic syntax and parameters

pop_backis a member function of the container class, and calling it requires no parameters.

Syntax format

void pop_back();

Parameter description

  • Parameter: No parameters

Function description

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

Example

Example 1: Basic usage - deleting the last 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;

    // Remove the last element
    numbers.pop_back();
    std::cout << "After pop_back(): ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    numbers.pop_back();
    std::cout << "After pop_back() again: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

Expected output:

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

Example 2: Safe Use of pop_back

Check whether the linked list is empty before use.

Example

#include <iostream>
#include <list>

void safePopBack(std::list<int>& lst) {
    if(!lst.empty()) {
        lst.pop_back();
        std::cout << "Delete successful" << std::endl;
    } else {
        std::cout << "The list is empty, cannot delete" << std::endl;
    }
}

int main() {
    std::list<int> data = {1, 2, 3};

    safePopBack(data);
    safePopBack(data);
    safePopBack(data);
    safePopBack(data); // It is empty now

    return 0;
}

Expected output:

Deletion successful
Deletion successful
Deletion successful
The linked list is empty, cannot delete

C++ container class <list>

other extensions