How to check if an array is empty or not in C++

The standard library contains a plethora of powerful containers and the std::array<> is one among them. The array container has several functions and one of them is the empty() function(array::empty()). This function is used to check if an array is empty.

The std::array<>::empty() function:

The function signature is similar to “bool array<template arguments >::empty()”. This function returns true if the array is empty. If the array contains elements, it returns false. Empty in the sense that the size of the array is zero. If it’s greater than one it always contains garbage values or default values if universal default initializer is used.

Also read: How to declare an empty array in C++

Example:

int main()
{
  std::array<int, 0> test;
  if (test.empty()) //checks if the array is empty
  {
    std::cout << "array contains no elements\n";
  }
  else
  {
    
    std::cout << "array contains" <<test.size()<<"elements\n";
  }
  
}

The test array is declared as an empty array. So the empty() function returns true and the if statement is executed and the output is produced as follows.

Output:

 array contains no elements.

If the size of the test array is changed to any number greater than zero the output changes as follows.

int main()
{
  std::array<int, 30> test{};
  if (test.empty())
  {
    std::cout << "array contains no elements\n";
  }
  else
  {
    
    std::cout << "array contains " <<test.size()<<" elements\n";
  }
  
}
Output:
array contains 30 elements

Some possible uses of empty() function:

The empty() function can be used to check for empty arrays as described in the following function template:

template<size_t r >
void print(std::array<int, r> &f)
{
  if (f.empty())
  {
    std::cout << "contains no elements\n";
  }
  else
  {
    std::cout << "values are\n";
    for (int x : f)
      std::cout << x << " ";
    std::cout << "\n";
  }

}

int main()
{
  std::array<int, 30> test;
  for (int i = 0; i < 30; i++)
    test[i] = 30 - i;
  std::array<int, 0> test2;
  std::cout << "printing test array..\n";
  print(test);
  std::cout << "printing test2 array\n";
  print(test2);
}
Output:


printing test array..
values are
30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

printing test2 array
contains no elements

Here the empty function is used to check if the array contains elements(not size zero). If not the elements are printed using a range-based for loop. Or else a message is displayed saying that it is an empty array.

Conclusion:

Although the function template can be used to work with different array sizes, it is not an ideal implementation. Usually, std::array is used for sizes that are fixed at compile time. It’s always a good idea to use std::vector for changing dimensions and it is a more powerful container than the std::array.

Leave a Reply

Your email address will not be published. Required fields are marked *