Mark unused positions in a vector

2

We assume that, in given implementation, the positions of a vector can contain values of -2^16 to 2^16 . You must "mark" unused positions (for example, put a *). However, given the range of values, setting the positions with -1, 0, 1 for example, is infeasible, as well as with symbols (due to the ASCII equivalence where, for example, * equals 42 decimal, which is in the range). What would be an efficient way to mark unused positions?

(The solution I thought was to use a value outside the range, but it would be a relatively high value, and I'm not sure it's a good idea.)

Edit: The language used is C and the data type is int

    
asked by anonymous 03.11.2015 / 05:17

1 answer

2

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 .

    
03.11.2015 / 13:02