Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ – How to check if array of unsigned int is empty or not

I have this:

std::uint32_t data[6];
std::map<std::string, std::variant<int, float, std::string, std::uint32_t> map_;

map_["data0"] = data[0] ? data[0] : 0;
map_["data1"] = data[1] ? data[1] : 0;
map_["data2"] = data[2] ? data[2] : 0;
map_["data3"] = data[3] ? data[3] : 0;
map_["data4"] = data[4] ? data[4] : 0;
map_["data5"] = data[5] ? data[5] : 0;

The idea of map_["data0"] = data[0] ? data[0] : 0; is to see if there is any value already set in data[0]if not to set 0.

However this does not work properly. Even if data[0] is not set it does not return ‘0’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any idea how can I check the array at specific index if the std::uint32_t is "initilized" or set ?

>Solution :

It is not possible to check if an integer type is initialized or not. An integer is not a pointer, and it is not pointer-like, it is not nullable. An uninitialized integer has an indeterminate value which cannot be inspected and which is distinct from the concept of null.

You need to track whether or not each element has a value yourself somehow.

Possible solutions include :

  • Using a sentinel value. For example, you could decide that the
    maximum representable value means "no value" and initialized all
    elements to that value.

  • Using flags. You could create another array of bool or a
    std::bitset to track which element has a value.

  • Using a different type which can encode more information, such as
    std::optional<std::uint32_t> data[6];.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading