using a vector instead of an array

Hello,

I have this delay class (it's for audio processing) using an array of doubles for a buffer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// MyDelay.h

class MyDelay
{
public:
	MyDelay();
	~MyDelay();
	double process(double input, double FB); // FB = feedback amount
	void setDelay(int);

private:
	double mBuffer2[44100] = {}; // array of doubles
	double* wptr = mBuffer2; // pointer to adress of first element of array
	double* rptr = mBuffer2;
	double out;
};

// MyDelay.cpp
#include "MyDelay.h"

double MyDelay::process(double input, double FB) {
        *wptr++ = input + out * FB; // move to next element
	out = *rptr++;

        // wrap around when end of array is reached
        if ((wptr - mBuffer2) >= 44100) { wptr -= 44100; }
	if ((rptr - mBuffer2) >= 44100) { rptr -= 44100; }
	return out;
}

void MyDelay::setDelay(int delayTime) {
	rptr = wptr - delayTime;
        // wrap around
	while (rptr < mBuffer2) { rptr += 44100; }
}


This works fine.
But actually I'd like to use a vector of doubles for the buffer instead of an array because the buffer has to be resizeable dynamically, which I can't do with an array afaik.

As I'm quite new to vectors (and actually C++ in general) how would I go about this ?
Can I perform the same pointer arithmetic using a vector instead of an array ?
Last edited on
http://en.cppreference.com/w/cpp/container/vector/data will give you a pointer to the start of the buffer.
Keep in mind that changing the size may reallocate the buffer, so you'll need to update your base pointers (or use an index instead).

> wrap around when end of array is reached
consider to use boost::circular_buffer
Thank you, this is new for me.
The pointer arithmetic works fine with this, nice.

Just an additional question:

Is the correct replacement for above line

 
if ((wptr - mBuffer2) >= 44100) { wptr -= 44100; }


the following

 
if ((wptr - &mBuffer2.front()) >=  44100) { wptr -= 44100; }


when using the vector instead of an array ?
That looks like it should work. If you want you could write mBuffer2.data() instead of &mBuffer2.front().
Last edited on
Ah yes, of course.

Marked as solved, thanks for the replies. :)
Topic archived. No new replies allowed.