I have a regular array of structs in C, in a program that runs every second and updates all the data in the structs. When a condition is met, one of the elements gets cleared and is used as a free slot for new element (in this case timers) that might come in at any point.
What I do is just to parse all the elements of the array looking for active elements requiring updates. But even if the amount of elements is small (<2000), I feel this is wasting time going through the inactive ones. Is there a way I can keep the array gap-free so I just need to iterate though the number of currently allocated elements?
Assuming the specific order of the elements does not matter, it can be done very easily.
If you have your array
Aand the number of active elementsN, you can then add an elementElike this:and remove the element at index
Ilike this:So how does this work? Well, it’s fairly simple. We want the array to only store active elements, so we may assume that the array is like that when we start doing either of these things.
Adding an element will always put it at the end, and since all elements currently in the array, as well as the newly added element, will be active, we can safely add one to the end.
Removing an element is done by moving the last element to take over the array index of the element we want to remove. Thus,
A[0..I-1]is active, as well asA[I+1..N], and by movingA[N]toA[I], the entire rangeA[0..N-1]is active (A[N]is not active, because it no longer exists – we moved it toA[I], and that’s why we decrease N by 1).If you’re removing elements while iterating over them to update them, note that you can only increment your loop counter after processing an element which doesn’t get removed, since otherwise, you would never process the moved elements.