Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::vector::empty — checking whether a vector is empty

Use `v.empty()` to check in constant time whether a vector has no elements. Reserved capacity does not affect the result.

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

Syntax

constexpr bool empty() const noexcept;

Include <vector> and call v.empty(). std::vector::empty is a member function that takes no arguments: it returns true if the vector has no elements and false otherwise. It runs in O(1), does not modify the vector, can be called on a const vector, and does not throw (noexcept since C++11). It is constexpr since C++20, so it can be used in constant evaluation when the full expression meets the requirements.

The result is equivalent to v.size() == 0 and v.begin() == v.end(). Prefer v.empty() when you only need a yes/no answer; use v.size() when you need the count. std::empty(v) (since C++17, <iterator>) is a separate non-member function that calls v.empty() for a vector.

A successful v.reserve(n) ensures capacity of at least n but creates no elements, so an empty vector stays empty. push_back or emplace_back adds an element; clear() destroys all elements without changing capacity. The same rules apply to std::pmr::vector, which uses a different allocator.

Check !v.empty() before calling v.back() or v.front(): calling either on an empty vector is undefined behavior in C++23. Never dereference v.end(); in an empty vector, v.begin() equals it. A nonempty vector does not make every index i valid: for v[i], the value of i after conversion to the vector’s size_type must be less than v.size(). A median function can explicitly reject empty input by throwing std::invalid_argument from <stdexcept>; empty() itself does not throw it.

Examples

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v;
    v.reserve(8);
    std::cout << std::boolalpha;
    std::cout << "reserve: " << v.empty() << '\n';

    v.push_back(42);
    if (!v.empty()) {
        std::cout << "back: " << v.back() << '\n';
    }

    v.clear();
    std::cout << "clear: " << v.empty() << '\n';
}

Result

reserve: true
back: 42
clear: true

`reserve(8)` leaves the vector empty. After inserting `42`, the guard lets `back()` run; after `clear()`, `empty()` returns `true` again.

Related lessons

  • C++ · Lesson 18 · Advanced · Version: 3
  • C++ · Lesson 23 · Advanced · Version: 3
  • C++ · Lesson 30 · Advanced · Version: 3

Sources