Namespaces
Variants

std:: empty

From cppreference.net
Iterator library
Iterator concepts
Iterator primitives
Algorithm concepts and utilities
Indirect callable concepts
Common algorithm requirements
(C++20)
(C++20)
(C++20)
Utilities
(C++20)
Iterator adaptors
Range access
(C++11) (C++14)
(C++14) (C++14)
(C++11) (C++14)
(C++14) (C++14)
(C++17) (C++20)
empty
(C++17)
(C++17)
定义于头文件 <array>
定义于头文件 <deque>
定义于头文件 <flat_map>
定义于头文件 <flat_set>
定义于头文件 <forward_list>
定义于头文件 <inplace_vector>
定义于头文件 <iterator>
定义于头文件 <list>
定义于头文件 <map>
定义于头文件 <regex>
定义于头文件 <set>
定义于头文件 <span>
定义于头文件 <string>
定义于头文件 <string_view>
定义于头文件 <unordered_map>
定义于头文件 <unordered_set>
定义于头文件 <vector>
template < class C >
constexpr auto empty ( const C & c ) - > decltype ( c. empty ( ) ) ;
(1) (C++17 起)
template < class T, std:: size_t N >
constexpr bool empty ( const T ( & array ) [ N ] ) noexcept ;
(2) (C++17 起)
template < class E >
constexpr bool empty ( std:: initializer_list < E > il ) noexcept ;
(3) (C++17 起)

返回给定范围是否为空。

1) 返回 c. empty ( )
2) 返回 false
3) 返回 il. size ( ) == 0

目录

参数

c - 具有 empty 成员函数的容器或视图
array - 任意类型的数组
il - 一个 std::initializer_list

返回值

1) c. empty ( )
2) false
3) il. size ( ) == 0

异常

1) 可能抛出实现定义的异常。

注释

针对 std::initializer_list 的重载是必需的,因为它没有名为 empty 的成员函数。

功能测试 标准 功能特性
__cpp_lib_nonmember_container_access 201411L (C++17) std::size() , std::data() , and std::empty()

可能的实现

第一版本
template<class C>
[[nodiscard]] constexpr auto empty(const C& c) -> decltype(c.empty())
{
    return c.empty();
}
第二版本
template<class T, std::size_t N>
[[nodiscard]] constexpr bool empty(const T (&array)[N]) noexcept
{
    return false;
}
第三版本
template<class E>
[[nodiscard]] constexpr bool empty(std::initializer_list<E> il) noexcept
{
    return il.size() == 0;
}

示例

#include <iostream>
#include <vector>
template<class T>
void print(const T& container)
{
    if (std::empty(container))
        std::cout << "Empty\n";
    else
    {
        std::cout << "Elements:";
        for (const auto& element : container)
            std::cout << ' ' << element;
        std::cout << '\n';
    }
}
int main()
{
    std::vector<int> c = {1, 2, 3};
    print(c);
    c.clear();
    print(c);
    int array[] = {4, 5, 6};
    print(array);
    auto il = {7, 8, 9};
    print(il);
}

输出:

Elements: 1 2 3
Empty
Elements: 4 5 6
Elements: 7 8 9

参见

检查范围是否为空
(定制点对象)