Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::vector::pop_back — Remove the last element

`pop_back()` removes the last element of a non-empty vector without returning its value. For a vector that stores a heap, `std::pop_heap` rearranges the elements; `pop_back()` reduces the size.

Version: ISO C++23; implementation support may vary

Syntax

constexpr void pop_back();

std::vector::pop_back is a non-const member function of std::vector from <vector>. It takes no arguments, returns void, and has been constexpr since C++20. It destroys the last element, reducing size() by one without changing capacity(). It takes constant time, O(1), and does not shift the remaining elements.

In C++23, calling pop_back() on an empty vector is undefined behavior. If the vector might be empty, check !v.empty() before using back() or pop_back(). If you need the value afterward, copy or move it into a separate object before removal. Pointers, references, and iterators to the removed element, as well as the old end() iterator, are invalidated. Handles to earlier elements remain valid.

On a non-empty heap built with the same ordering, std::pop_heap from <algorithm> puts the root value in the last position and restores the heap property over the preceding positions. It neither erases an element nor changes the size. Then v.back() accesses the former root value and v.pop_back() removes the last element. Calling pop_back() alone removes the last element, not necessarily the root.

Examples

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{4, 9, 2};
    std::make_heap(v.begin(), v.end());

    if (!v.empty()) {
        std::pop_heap(v.begin(), v.end());
        const int removed = v.back();
        std::cout << "After pop_heap: " << v.size() << '\n';
        v.pop_back();
        std::cout << "After pop_back: " << v.size() << '\n';
        std::cout << "Removed: " << removed << '\n';
    }
}

Result

After pop_heap: 3
After pop_back: 2
Removed: 9

After `std::pop_heap`, the size is still 3. The program copies 9 before removing the last element, so it can print the value after the size drops to 2.

Related lessons

  • C++ · Lesson 34 · Advanced · Version: 3

Sources