1

I'm seeking for a proper structure for a big array which will be frequently updated. Thanks for your help! Here's the background: I want to draw a continuous curve to represent a sound wave in a certain time period. For the accuracy, the array length will be nearly 44100(the CD format).And I just want to represent the last second wave, so the array will be updated very frequently - for every 1/44100 sec, the first element will be eliminated and a new last element will be inserted to the array.

For avoiding the frequent "malloc/realloc/new", what my current solution is using an Circular Queue which has a fixed size as 44100, but somehow I don't feel this is most proper solution, if I want to dynamically resize the queue, it will be a heavy cost. This kind of situation should be quite often, I think there maybe some good patent for this issue. Thanks guys!

4

1 回答 1

2

I assume you're always having a fixed number of items in the array. As such I'd just use a ring buffer in any case (not sure whether that's what you refer to as a "Circular Queue", but I assume you'd use a dynamic length? If so, why? Is there no specific absolute (and practical) maximum?), i.e. a static array with a variable entry point as its start:

const unsigned int buffer_length = 500000;
float *buffer = new float[buffer_length];

unsigned int buffer_write = 0;

// append a value...
buffer[buffer_write] = my_value;
// ...and move the write/end position:
buffer_write = (buffer_write + 1) % buffer_length;

To output/use the values, you can use the following formula for index of the first entry to read:

unsigned int start_position = (buffer_length + buffer_write - length_to_read) % buffer_length;

To iterate, you just add position after position, again using modulo to jump back to the beginning of the array.

于 2013-01-01T23:39:46.513 回答