I have a sparsely populated vector that I populated via hashing, so elements are scattered randomly in the vector. Now what I want to do is iterate over every element in that vector. What I had in mind was essentially condensing the vector to fit the number of elements present, removing any empty spaces. Is there a way I can do this?
+1
A:
Either you save the additionally needed information during insertion of the elements (e.g. links to the previous / next element compared to a linked list) or you make one pass over all the elements and remove the unnecessary ones.
The first solution costs you some space (approx. 8 bytes / entry), the second costs you one pass over all elements. Depending on the scenario, one or both possibilities might not be useful.
Tobias Langner
2010-04-01 09:02:35
next to the space-cost, you also have the bookkeeping cost during insert/erase (including finding the previous/next entries).
stefaanv
2010-04-01 09:20:04
+1
A:
You can condense using a version of run-length encoding.
You go over the original vector and create a new "condensed" vector which contains alternating values - a value from the original and a count of the empty spaces to the next value. For example this:
3 - - - - 4 - - 7 3 - - - 9 -
turns to this:
3 4 4 2 7 0 3 3 9 1
shoosh
2010-04-01 09:04:24