Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range-based loop for std::queue

Tags:

c++

c++11

queue

I'm trying to look for a substitute in std::vector in my project, and I found out that std::queue is what I'm looking for.

I have lots of function that uses range-based loop for iteration and I'm trying to maintain it as far as I can.

I try to compile a range-based loop in std::queue but all I get are compile errors

error: no matching function for call to 'begin(std::queue&)'

Doesn't std::queue support range base loop?

I did try Google search but didn't find any topic regarding to this.

Update:

My compiler is GCC v4.7.1

-std=c++11 is enabled

And here's the faulty test code:

std::queue<int> Q;

for (int i = 0;i < 10; ++i)
    Q.push(i);

std::cout << "\nqueue contains: ";
for (auto i : Q)
    std::cout << i << ", ";
like image 930
mr5 Avatar asked Dec 23 '13 11:12

mr5


1 Answers

Well, the answer is actually pretty simple: there is no function begin() in std::queue and there isn't any overload of std::begin taking a std::queue either. You can have a look at the documentation.

The core problem is that std::queue is not meant to be iterated over. It exists to satisfy other needs. If you really need to iterate over it, you should just use the underlying container (by default std::deque) which supports iteration and for which your code would be valid.

like image 110
Morwenn Avatar answered Oct 01 '22 12:10

Morwenn