Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check std::array is declared but not explicitly initialized

Tags:

c++

arrays

stl

std::array has a built-in method empty() to check if the array is empty. As shown in the example copied from here:

#include <array>
#include <iostream>
 
int main()
{
    std::array<int, 4> numbers {3, 1, 4, 1};
    std::array<int, 0> no_numbers;
 
    std::cout << std::boolalpha;
    std::cout << "numbers.empty(): " << numbers.empty() << '\n';
    std::cout << "no_numbers.empty(): " << no_numbers.empty() << '\n';
}

Are there any ways to check if the array is declared, with some fixed size, but not explicitly initialized?

Say, something like this?

std::array<int,4> a;
std::array<int,4> b;
a = {1,2,3,4}; //a holds some explicit values
//do not assign values to b
//how to tell the different state of a and b?
like image 510
Xuhang Avatar asked Feb 20 '26 19:02

Xuhang


1 Answers

No. std::array<T, N>::empty() where N!=0 will always return false. https://en.cppreference.com/w/cpp/container/array/empty "Checks if the container has no elements, i.e. whether begin() == end()."

Similarly std::array<T, 0>::empty() will always return true, because begin() == end().

like image 103
Mooing Duck Avatar answered Feb 23 '26 11:02

Mooing Duck