如何在for循环中迭代`std :: stack`元素?

时间:2013-08-08 11:53:10

标签: c++ for-loop stl stack moving-average

我正在写一个FIR滤波器,它应该计算输入序列的running average

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);
}

3 个答案:

答案 0 :(得分:1)

您可以使用std::deque代替堆栈,使用push_frontpop_front

答案 1 :(得分: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;
};

答案 2 :(得分:0)

在第一个循环中推送堆栈上的值。所以你可以在第二个循环中弹出它们并将它们加起来并计算它们以获得平均值。