Iterating through std queue

22,000

Solution 1

std::deque supports efficient insert and removal at the beginning and end of the data structure. You can do queue operations manually using push_back and pop_front.

A queue uses a deque internally by default. It's a wrapper that only exposes queue operations (hence why you can't iterate over it). I asked a similar question a while back, and the best answer gave me good insight into the real use of std::queue. One should use std::queue not because one needs a queue, but to make it clear that only queue-like operations are legal on a given data structure. It sounds like you need more freedom than that, so go with deque, list, or some other structure with O(1) insert and remove at both ends.

Solution 2

you can use std::list with push_front and pop_back

Solution 3

std::queue is a container adaptor. It uses std::deque as the default underlying container. Access to this container isn't possible and thus isn't iteration in any way.

The best way is to use a std::deque or std::list and manage the queue behaviour yourself. Possibly provide your own wrapper around it.

Share:
22,000

Related videos on Youtube

Hanut
Author by

Hanut

Updated on July 15, 2020

Comments

  • Hanut
    Hanut almost 4 years

    I'm trying to use BOOST_FOREACH for iterating through the std::queue. But there isn't iterators in that class cause I have an error:

    std::queue<std::string> someList;
    BOOST_FOREACH(std::string temp, someList)
    {
       std::cout << temp;
    }
    
    >no matching function for call to begin(...)
    >no type named ‘iterator’ in ‘class std::queue<std::basic_string<char> >’
    

    I need in structure like: the first comes, the first goes away.

  • Makesh
    Makesh about 7 years
    I thought queue is simpler (perf + mem) than deque. But after your answer (and verified through header file), I think there is no difference in perf and memory regardless of queue or deque, except restrictions over some operations in case of Queue.

Related