example2_signal_processing.cpp

 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
86
87
#include <iostream>
#include <vector>
#include <cstddef>

template<typename T>
class CircularBuffer {
private:
    std::vector<T> data;
    size_t head = 0;
    size_t tail = 0;
    size_t max_size;
    bool full = false;

public:
    CircularBuffer(size_t size) : data(size), max_size(size) {}

    void push(T item) {
        data[head] = item;
        if (full) {
            tail = (tail + 1) % max_size;
        }
        head = (head + 1) % max_size;
        full = head == tail;
    }

    T pop() {
        if (empty()) {
            throw std::runtime_error("Buffer is empty");
        }
        T item = data[tail];
        full = false;
        tail = (tail + 1) % max_size;
        return item;
    }

    T front() const {
        if (empty()) {
            throw std::runtime_error("Buffer is empty");
        }
        return data[tail];
    }

    size_t size() const {
        if (full) return max_size;
        if (head >= tail) return head - tail;
        return max_size + head - tail;
    }

    bool empty() const {
        return (!full && (head == tail));
    }
};

class MovingAverageFilter {
private:
    CircularBuffer<double> buffer;
    size_t window_size;

public:
    MovingAverageFilter(size_t size) : buffer(size), window_size(size) {}

    double process(double input) {
        buffer.push(input);
        double sum = 0.0;
        size_t count = 0;
        for (size_t i = 0; i < window_size && i < buffer.size(); ++i) {
            double value = buffer.front();
            sum += value;
            buffer.pop();
            buffer.push(value);
            ++count;
        }
        return sum / count;
    }
};

int main() {
    MovingAverageFilter filter(5);
    double inputs[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
    
    for (double input : inputs) {
        double output = filter.process(input);
        std::cout << "Input: " << input << ", Output: " << output << std::endl;
    }

    return 0;
}
Back to circular_buffer