Well, there are some solutions I see for this: 1) Use a value out of range; 2) use an auxiliary vector for this or; 3) use a more complex data structure.
You should also be aware of the Null Object project pattern .
Approach 1
If you are using an integer array (which allows values from -2^31
to 2^31 - 1
), but the values that interest you are just a range of these values, then you can use one of the values out of range to represent an unfilled value. Usually the values 0 or -1 are used for this purpose (or if the data is not numeric, you can use NULL
, an empty string, the address of a struct with the data blank, the address of a function that does not does nothing, or some other type of data that means empty, unfilled or undefined). In case of integers, when 0 or -1 are valid, some other number outside the range can be used.
This is the approach that most saves memory, and is also the most common approach.
Approach 2
On the other hand, if you can not or do not want to use a value out of range, then maybe an auxiliary vector will do. The simplest way is to create a vector of int
, short
or char
the same size as its original vector and fill it with 0 where the value of its main array must be disregarded and considered unfilled and 1 otherwise.
To save memory, using a more sophisticated implementation, it is possible to work directly with bits, so as to have a char
vector where each position of the helper vector represents 8 positions of the original vector.
Approach 3
Finally, the last approach is to do something like this:
typedef struct {
char usado;
int valor;
} Elemento;
And so, instead of using an array as int[]
, you'll use Elemento[]
. This approach consumes one more byte for each element you want to use (which means that 7 bits of memory are wasted per element).
This memory wastage can be avoided by using eight values together with just one character to track what was marked in every% w_ of%, but in this case approach 2 becomes simpler and more efficient in practice .