std::empty
|
在标头
<array> 定义 |
||
|
在标头
<deque> 定义 |
||
|
在标头
<forward_list> 定义 |
||
|
在标头
<iterator> 定义 |
||
|
在标头
<list> 定义 |
||
|
在标头
<map> 定义 |
||
|
在标头
<regex> 定义 |
||
|
在标头
<set> 定义 |
||
|
在标头
<span> 定义 |
(C++20 起)
|
|
|
在标头
<string> 定义 |
||
|
在标头
<string_view> 定义 |
(C++17 起)
|
|
|
在标头
<unordered_map> 定义 |
||
|
在标头
<unordered_set> 定义 |
||
|
在标头
<vector> 定义 |
||
| (1) | ||
|
template <class C>
constexpr auto empty(const C& c) -> decltype(c.empty()); |
(C++17 起) (C++20 前) |
|
|
template <class C>
[[nodiscard]] constexpr auto empty(const C& c) -> decltype(c.empty()); |
(C++20 起) | |
| (2) | ||
|
template <class T, std::size_t N>
constexpr bool empty(const T (&array)[N]) noexcept; |
(C++17 起) (C++20 前) |
|
|
template <class T, std::size_t N>
[[nodiscard]] constexpr bool empty(const T (&array)[N]) noexcept; |
(C++20 起) | |
| (3) | ||
|
template <class E>
constexpr bool empty(std::initializer_list<E> il) noexcept; |
(C++17 起) (C++20 前) |
|
|
template <class E>
[[nodiscard]] constexpr bool empty(std::initializer_list<E> il) noexcept; |
(C++20 起) | |
返回给定的范围是否为空。
1) 返回 c.empty()
2) 返回 false
3) 返回 il.size() == 0
参数
| c | - | 拥有 empty 成员函数的容器或视图 |
| array | - | 任意类型的数组 |
| il | - | 一个 initializer_list |
返回值
若范围不含有任何元素则为 true 。
异常
1) 可能抛出实现定义的异常。
注解
需要对 std::initializer_list 的重载,因为它无成员函数 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 << "Elements:\n"; for ( const auto& element : container ) std::cout << element << '\n'; } else { std::cout << "Empty\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
参阅
|
(C++20)
|
检查范围是否为空 (定制点对象) |