std::empty
来自cppreference.com
<tbody>
</tbody>
| 在标头 <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)
false3)
il.size() == 0异常
1) 可能会抛出由实现定义的异常。
注解
需要对 std::initializer_list 的重载,因为它没有成员函数 empty。
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_nonmember_container_access |
201411L |
(C++17) | std::size(), std::data(), 和 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 << "空\n";
else
{
std::cout << "元素:";
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);
}
输出:
元素: 1 2 3
空
元素: 4 5 6
元素: 7 8 9
参阅
(C++20) |
检查范围是否为空 (定制点对象) |