Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through std queue

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.

like image 784
Max Frai Avatar asked Jun 01 '10 14:06

Max Frai


2 Answers

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.

like image 157
Michael Kristofik Avatar answered Sep 23 '22 02:09

Michael Kristofik


you can use std::list with push_front and pop_back

like image 25
chub Avatar answered Sep 26 '22 02:09

chub