5

我正在编写一个 FIR 滤波器,它应该计算输入序列的运行平均值。

class RunningAverager
{
    public:
        RunningAverager(uint64_t FilterOrder)
        {
            for (uint64_t i=0; i<FilterOrder; i++)
            {
                Registers.push(0);
            }
        }
        uint64_t GetAverage(uint64_t NewInput)
        {
            Registers.push(NewInput);
            Registers.pop();
            return GetAverage();
        }
        uint64_t GetAverage() const
        {
            uint64_t Sum = 0;
            //for (uint64_t i=0; i<Registers.size(); i++)       <-- Works
            for (std::stack<uint64_t>::const_reference ref=Registers.begin(); ref!=Registers.end(); ???)
            {   // begin() and end() methods do not exist for std::stack
                //Sum += Registers[i];      Doesn't work, because the [] operator is not overloaded.
                Sum += ref;
            }
            return Sum / Registers.size();
        }
    private:
        std::stack<uint64_t> Registers;
};

我在迭代std::stack对象时遇到问题Registers。与其他 STL 容器不同,它不提供迭代器或随机访问运算符。

我如何循环和std::stack反对?

一个示例用法:

RunningAverager ra(10);

while(...)
{
    FilteredSpeed = ra.GetAverage(ActualSpeed);
}
4

3 回答 3

1

std::deque对于这个特定的应用程序使用容器更容易。

class RunningAverage
{
    public:
        RunningAverage(uint64_t Order)
        {
            for (uint64_t i=0; i<Order; i++)
            {
                Registers.resize(Order, 0);
            }
        }
        uint64_t GetAverage(uint64_t NewInput)
        {
            Registers.push_back(NewInput);
            Registers.pop_front();
            return GetAverage();
        }
        uint64_t GetAverage() const
        {
            uint64_t Sum = 0;
            for (std::deque<uint64_t>::const_iterator it=Registers.begin(); it<Registers.end(); ++it)
            {
                Sum += *it;
            }
            return Sum / Registers.size();
        }
    private:
        std::deque<uint64_t> Registers;
};
于 2013-08-08T12:22:31.990 回答
1

您可以使用 astd::deque代替堆栈,使用push_frontand pop_front

于 2013-08-08T11:58:33.630 回答
0

您在第一个循环中将值压入堆栈。因此,您可以在第二个循环中将它们弹出并将它们相加并计算它们以获得平均值。

于 2013-08-08T11:55:14.380 回答