Reputation: 1
I know we can not iterate easily in STL Queue, but I want to do something like this:
void myFun(Node* root) {
queue<pair<int, Node*>> myQueue;
myQueue.push(make_pair(0, root));
auto it = myQueue.front();
}
This works, however, what should I use instead of the auto
keyword for the queues?
We use something like this for maps:
map<int, Node*>::iterator it = myMap.begin();
But
queue<pair<int, Node*>>::iterator it = myQueue.front();
This does not work and throws error:
‘iterator’ is not a member of ‘std::queue<std::pair<int, Node*> >’
queue<pair<int, Node*>>::iterator it = myQueue.front();
What's the correct syntax?
Upvotes: 0
Views: 443
Reputation: 76305
std::queue
does not provide access to its internals. It's interface is that of a queue: you push elements into it, and you pop elements out of it. That's all. If you need a container that lets you look at its contents, `std::queued isn't the appropriate choice.
Upvotes: 0
Reputation: 16670
You should use pair<int, Node*> &
, (possibly const) since that's what front()
returns. None of the containers (or container adaptors) have a front()
method that returns an iterator.
What are you trying to accomplish?
Upvotes: 0
Reputation: 60238
The front member of std::queue
doesn't return an iterator at all, it returns a reference to the first element in the queue. So auto
would just be the type inside the queue
std::pair<int, Node*> it = myQueue.front();
This makes a copy of the element, but you can also take a reference, or a const reference, to that element.
As there are no queue
member functions that return an iterator, you'll have to look at all the elements with a sequence of front
and pop
calls.
Upvotes: 2