std::empty - cppreference.com
From cppreference.com
| Defined in header |
||
| Defined in header |
||
| Defined in header |
(since C++23) |
|
| Defined in header |
(since C++23) |
|
| Defined in header |
||
| Defined in header |
(since C++26) |
|
| Defined in header |
||
| Defined in header |
||
| Defined in header |
||
| Defined in header |
(since C++26) |
|
| Defined in header |
||
| Defined in header |
||
| Defined in header |
(since C++20) |
|
| Defined in header |
(since C++23) |
|
| Defined in header |
||
| Defined in header |
||
| Defined in header |
||
| Defined in header |
||
| Defined in header |
||
| Defined in header |
||
template< class C > constexpr auto empty( const C& c ) noexcept(noexcept(c.empty())) -> decltype(c.empty()); |
(1) | (since C++17) |
template< class T, std::size_t N > constexpr bool empty( const T (&array)[N] ) noexcept; |
(2) | (since C++17) |
Returns whether the given range is empty.
1) Returns c.empty().
2) Returns false.
Parameters
| c | - | a container or view with an empty member function
|
| array | - | an array of arbitrary type |
Return value
1) c.empty()
2) false
Exceptions
1) What and when the underlying c.empty() call throws.
Notes
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_nonmember_container_access |
201411L |
(C++17) | std::size(), std::data(), and std::empty()
|
__cpp_lib_initializer_list |
202511L |
(C++26) (DR11) |
data and empty member functions of std::initializer_list;removing unnecessary free functions for std::initializer_list[1]
|
Possible implementation
| First version |
|---|
template<class C> [[nodiscard]] constexpr auto empty(const C& c) noexcept(noexcept(c.empty())) -> decltype(c.empty()) { return c.empty(); } |
| Second version |
template<class T, std::size_t N> [[nodiscard]] constexpr bool empty(const T (&array)[N]) noexcept { return false; } |
Example
#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); }
Output:
Elements: 1 2 3 Empty Elements: 4 5 6 Elements: 7 8 9
Defect report
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| P3016R6 | C++17 | 1) non-member std::empty overload was provided for std::initializer_list2) std::empty was not required to propagate exception specification
|
1) removed 2) required |