8

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.

Max Frai
  • 61,946
  • 78
  • 197
  • 306

3 Answers3

19

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.

Community
  • 1
  • 1
Michael Kristofik
  • 34,290
  • 15
  • 75
  • 125
  • 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. – Makesh Feb 23 '17 at 07:32
4

you can use std::list with push_front and pop_back

chub
  • 767
  • 6
  • 11
1

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
  • 58,701
  • 10
  • 113
  • 156