std :: queue iteration

问题描述 投票:60回答:8

我需要迭代std::queue。 www.cplusplus.com说:

默认情况下,如果没有为特定队列类指定容器类,则使用标准容器类模板deque。

那么我可以以某种方式到达队列的底层deque并迭代它吗?

c++ queue iteration c++-standard-library
8个回答
61
投票

如果你需要迭代queue,那么你需要的不仅仅是队列。标准容器适配器的要点是提供最小的接口。如果你还需要进行迭代,为什么不使用deque(或列表)呢?


32
投票

虽然我同意其他人的看法,直接使用可迭代容器是首选解决方案,但我想指出,C ++标准保证为自己动手解决方案提供足够的支持,以防您出于任何原因需要它。

也就是说,您可以从std::queue继承并使用其受保护的成员Container c;来访问底层容器的begin()和end()(前提是存在此类方法)。这是一个适用于VS 2010和tested with ideone的示例:

#include <queue>
#include <deque>
#include <iostream>

template<typename T, typename Container=std::deque<T> >
class iterable_queue : public std::queue<T,Container>
{
public:
    typedef typename Container::iterator iterator;
    typedef typename Container::const_iterator const_iterator;

    iterator begin() { return this->c.begin(); }
    iterator end() { return this->c.end(); }
    const_iterator begin() const { return this->c.begin(); }
    const_iterator end() const { return this->c.end(); }
};

int main() {
    iterable_queue<int> int_queue;
    for(int i=0; i<10; ++i)
        int_queue.push(i);
    for(auto it=int_queue.begin(); it!=int_queue.end();++it)
        std::cout << *it << "\n";
    return 0;
}

9
投票

您可以将原始队列保存到临时队列。然后,您只需在临时队列上执行常规弹出即可通过原始队列,例如:

queue tmp_q = original_q; //copy the original queue to the temporary queue

while (!tmp_q.empty())
{
    q_element = tmp_q.front();
    std::cout << q_element <<"\n";
    tmp_q.pop();
} 

最后,tmp_q将为空,但原始队列未被触及。


1
投票

为什么不只是复制要迭代的队列,并一次删除一个项目,随时打印它们?如果要在迭代时对元素执行更多操作,则队列是错误的数据结构。


-1
投票

如果需要迭代队列...队列不是您需要的容器。 你为什么选择队列? 你为什么不带一个可以迭代的容器?


1.如果你选择一个队列然后你说你想把一个容器包装成一个'队列'界面: - 前 - 后 - 推 - 弹 - ...

如果您还想迭代,则队列的接口不正确。队列是提供原始容器的受限子集的适配器

2.队列的定义是FIFO,根据定义,FIFO不可迭代


-1
投票

我用的是这样的东西。不是很复杂,但应该工作。

    queue<int> tem; 

    while(!q1.empty()) // q1 is your initial queue. 
    {
        int u = q1.front(); 

        // do what you need to do with this value.  

        q1.pop(); 
        tem.push(u); 
    }


    while(!tem.empty())
    {
        int u = tem.front(); 
        tem.pop(); 
        q1.push(u); // putting it back in our original queue. 
    }

它会起作用,因为当你从q1弹出一些东西并将它推入tem时,它就成了tem的第一个元素。所以,最终tem成为q1的复制品。


-2
投票

简而言之:不。

有一个hack,使用向量作为底层容器,所以queue::front将返回有效的引用,将其转换为指针迭代直到<= queue::back


-2
投票

std::queue是一个容器适配器,您可以指定使用的容器(默认使用deque)。如果您需要适配器之外的功能,那么只需直接使用deque或其他容器即可。

© www.soinside.com 2019 - 2024. All rights reserved.