Below is the direct conversion of your C code to a C++ implementation, still retaining the basic logic of a filter function, with some C++ specific improvements for better maintainability and usability.
In C++, we will make use of a class to encapsulate the filter function logic. This allows us to keep the static variables encapsulated within the instance of the class, rather than them being static in the global sense. It also brings the benefits of object-oriented programming including data encapsulation and potential for code reuse.
Here’s how the C++ code could look:
#include <array>
using std::array;
class Filter {
public:
Filter() : index(0), sum(0), buffer{} {} // Constructor to initialize values
int operator()(int x) {
// Update the running sum by subtracting the oldest value and adding the new value
sum = sum - buffer[index] + x;
// Update the buffer with the new input
buffer[index] = x;
// Increment and wrap index
index = (index + 1) % N;
// Return the filtered value
return sum / N;
}
private:
static constexpr int N = 4;
int index;
int sum;
array<int, N> buffer; // Buffer for past values
};
#include <iostream>
int main() {
Filter filter;
// Example usage of the filter
std::cout << "Filtered value: " << filter(10) << std::endl;
std::cout << "Filtered value: " << filter(20) << std::endl;
std::cout << "Filtered value: " << filter(30) << std::endl;
std::cout << "Filtered value: " << filter(40) << std::endl;
std::cout << "Filtered value: " << filter(50) << std::endl; // As the window slides, the older value gets replaced.
return 0;
}
Key Features and Improvements in the C++ Version:
-
Object-Oriented Approach: Instead of using static global variables and a function, we encapsulate the functionality within a Filter class. This class manages its state internally and provides an interface to apply the filter via the operator() method. This lets the filter be used similar to a function while maintaining the state encapsulated in an instance.
-
Constructor Initialization: In the constructor Filter(), the index and sum are initialized, and the buffer is default-initialized (automatically to zero for int).
-
std::array Instead of C-style Array: This provides a modern, safer alternative to C-style arrays. std::array comes with benefits like standard container functions and bounds-checking in debug modes.
-
Use of constexpr for Constants: static constexpr is used for the constant N which specifies the array size and related modulo operations, ensuring it's evaluated at compile time.
-
Operator Overloading (operator()): By overloading the function call operator, instances of Filter can be used similarly to calling a function, providing a clean and intuitive interface for filtering values.
This C++ design is more robust, safer, and maintainable, making use of language features appropriate for these types of tasks.