简体   繁体   中英

How to find it the array of size 'x' is completely filled or not, in C++?

int size = 10;
int arr[size] = {};
for(int i = 0; i < size; i++)
    arr[i] = i;

Now how do I find if the array is filled or not in the code. I know arr[size - 1] = 9 , but what is arr[size] and beyond? How do i compare arr[size] ==? using if statement, or is there another way? I am using ubnutu and this is the compiler g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0 .

When you use raw arrays, it is your responsibility to handle that memory and keep track of what has been written. This sounds like a good usecase for a std:vector instead. Especially by making use of its reserve(size) function. With reserve you tell how much memory to keep for your data and then you can fill that array with push_back(content) , retrieving the current number of filled elements with size() (of course reserve is just an optimization to avoid re-allocating the memory because even without it, a vector will dynamically grow).

Now how do I find if the array is filled or not

All arrays are always "filled". An array of N elements contains N elements and no less.

An element of trivial type could have an indeterminate value. There is no way to find whether a value is indeterminate. The behaviour of reading an indeterminate value is undefined.

In your example, you value initialised the array, so it is filled with value initialised elements (before the loop where you change the values). Which in case of int means that the array is filled with zeroes. You can test whether an element is zero or not like this:

if (arr[i])
    // not zero
else
    // is zero

but what is arr[size] and beyond?

There is no " arr[size] and beyond" because those indices are outside the bounds of the array. The behaviour of accessing values outside the bounds of an array is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM