C++ std::array::empty
The std::array::empty
function checks whether a std::array
is empty. Since std::array
has a fixed size determined at compile time, this function always returns false
unless the size of the array is explicitly defined as 0
. It provides a convenient way to check the emptiness of arrays in a generic programming context.
Syntax of std::array::empty
</>
Copy
constexpr bool empty() const noexcept;
Parameters
The std::array::empty
function does not take any parameters.
Return Value
Returns a boolean value:
true
: If the size of the array is 0.false
: If the size of the array is greater than 0.
Examples for std::array::empty
Example 1: Checking if a std::array is Empty
This example demonstrates how to use the empty
function to check whether a std::array
is empty:
</>
Copy
#include <iostream>
#include <array>
int main() {
std::array<int, 0> arr; // Define an array with size 0
if (arr.empty()) {
std::cout << "The array is empty." << std::endl;
} else {
std::cout << "The array is not empty." << std::endl;
}
return 0;
}
Explanation:
- Define a
std::array
: An array of size0
is defined. - Use
empty()
: Theempty()
function checks whether the size of the array is0
. - Output the result: Since the array size is
0
, the function returnstrue
, and the output indicates that the array is empty.
Output:
The array is empty.
Example 2: Using std::array::empty in a Conditional Statement
This example demonstrates checking whether a std::array
with non-zero size is empty:
</>
Copy
#include <iostream>
#include <array>
int main() {
std::array<int, 5> arr = {1, 2, 3, 4, 5}; // Define an array with 5 elements
if (arr.empty()) {
std::cout << "The array is empty." << std::endl;
} else {
std::cout << "The array is not empty." << std::endl;
}
return 0;
}
Explanation:
- Define a
std::array
: An array with 5 elements is defined and initialized. - Use
empty()
: Theempty()
function checks whether the array size is0
. - Output the result: Since the array size is greater than
0
, the function returnsfalse
, and the output indicates that the array is not empty.
Output:
The array is not empty.
Exception Handling in std::array::empty
The std::array::empty
function does not throw exceptions as it is marked noexcept
. This ensures safe usage when checking if a std::array
is empty.