Given an input device (basically a keyboard) that reports keyup and keydown, how may I most efficiently store and retrieve information about which keys are currently depressed? My first thought was a dynamic array, but maintaining and searching a dynamic array seems like a serious drain on resources.
Many thanks in advance for any help
Joe
7
A fixed-length array will work just fine, since the number of keys can’t change.
So, make an array, call it depressed, of length N, where N is the number of keys on your input device.
When key X is depressed, set depressed[X] to True.
When key X is released, set depressed[X] to False.
To report the True/False state of any given key, you’ll need a mapping from user-/API-level names, to indices into your array.
e.g. MOTOR_REVERSE_TOGGLE -> position 6 in your array.
As for efficiency, an array should be adequate for space, unless you’ve got very tight memory restrictions on whatever device you’re programming. In that case, you’d use a bitfield to store the data. Basically, it’s the same as your array, except instead of words being set to True or False (which would end up a some magic numbers, say for example 11111111 and 00000000), you set individual bits in a word to 1 or 0.