views:

226

answers:

3

Hi, 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.

+3  A: 

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.

Kristo
+1  A: 

you can use std::list with push_front and pop_back

chub
+1  A: 

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.

pmr