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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #include <iostream>
struct fir_filter {
public:
fir_filter(): coeffs(NULL), num_coeffs(0), count(0) {}
~fir_filter() {
if (coeffs != NULL) {
delete[] coeffs;
}
}
public:
void add_coeff(short new_coeff) {
if (num_coeffs > 0) {
if (count < num_coeffs) {
coeffs[count] = new_coeff;
++count;
} else { // no realloc in C++, you must destroy and recreate
short* tmp;
num_coeffs += 2;
tmp = new short[num_coeffs]; // maybe test if is ok
for(size_t i=0; i < count; ++i) { tmp[i] = coeffs[i]; }
delete[] coeffs;
coeffs = tmp;
coeffs[count] = new_coeff;
++count;
}
} else {
coeffs = new short[4]; // maybe test if is ok
coeffs[0] = new_coeff;
count = 1;
num_coeffs = 4;
}
}
friend std::ostream& operator<< (std::ostream&, fir_filter const&);
public: // pour 1 structure, les membres sont souvent publiques
short* coeffs;
short num_coeffs;
private:
size_t count;
};
std::ostream& operator<< (std::ostream& os, fir_filter const& str) {
os << "[ ";
for(size_t i=0; i < str.count; ++i) { os << str.coeffs[i] << " "; }
os << "]";
return os;
}
int main()
{
fir_filter str;
std::cout << "init fir_filter: " << str << std::endl;
str.add_coeff((short) (32768 * -0.635640527595689));
str.add_coeff((short) (32768 * -0.20976263263201292));
str.add_coeff((short) (32768 * 0.6981598830670951));
str.add_coeff((short) (32768 * -0.20976263263201292));
str.add_coeff((short) (32768 * -0.635640527595689));
std::cout << "fir_filter: " << str << std::endl;
for(size_t i=0; i < 4; ++i) { str.add_coeff(32 * i); }
std::cout << "fir_filter: " << str << std::endl;
return 0;
} |