tags:

views:

71

answers:

2

In my project I use the std::queue class. I would like to know what happen if I do the following.

  • Get a a pointer of a element inside the queue (note: a pointer and not a iterator).
  • I make modification in the queue like push and pop in the queue (pop element which is not the pointed by the previous pointer)

Does my pointer still point on the same element I specify in the beginning ? Is it defined by the queue specification?

+1  A: 

Just use a std::deque instead. std::queue is designed to prevent the user from doing anything non-queue like.

Michael Anderson
Ok, but it does not answer my question actually. (std::queue use std::dequeue). If i got a reference (pointer) to an element and If I do a push/pop action. does the reference get invalidated ?
Phong
Ah sorry I misunderstood your question. An iterator or pointer to an element of a default queue may get invalidated on push or pop. You can however create a std::queue<T,std::list<T> > that will not invalidate the iterators or pointers into the container.
Michael Anderson
+1  A: 

std::queue uses a sequence container for its implementation. By default, std::deque is used. With a std::deque, so long as all the insertions and erasures are at the beginning or the end of the container, references and pointers to elements in the container are not invalidated.

However, I don't know how you are going to get a pointer to an element in the queue; it doesn't provide functionality for that (you can only get a reference to the first and last elements in the queue).

James McNellis
Actually I must generate a wrapper C for my library C++ which use the std::queue. And the user want to be able to use the data through a pointer (he like to modify the spec as he want). Was planing to use the iterator to get the pointer to the element but without the insurance it is ok or not...
Phong
@Phong: `std::queue` does not have iterators.
James McNellis
@James: My mistake, you're right.
Phong