std::vector<T,Allocator>::empty

< cpp‎ | container‎ | vector

bool empty() const;
(C++11 前)
bool empty() const noexcept;
(C++11 起)
(C++20 前)
[[nodiscard]] constexpr bool empty() const noexcept;
(C++20 起)

检查容器是否无元素,即是否 begin() == end()

参数

(无)

返回值

若容器为空则为 true ,否则为 false

复杂度

常数。

示例

下列代码用 empty 检查 std::vector<int> 是否含有任何元素:

#include <vector>
#include <iostream>
 
int main()
{
    std::cout << std::boolalpha;
    std::vector<int> numbers;
    std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\n';
 
    numbers.push_back(42);
    std::cout << "After adding elements, numbers.empty(): " << numbers.empty() << '\n';
}

输出:

Initially, numbers.empty(): true
After adding elements, numbers.empty(): false

参阅

返回容纳的元素数
(公开成员函数)