I am implementing a variant of toposort, which needs a structure to hold elements with no incoming edges. Both queue
and stack
seem fine for this purpose, as the order in which they are taken out does not matter. The question is: is any of them significantly faster than the other?

- 968
- 1
- 11
- 33
-
2Answer: most probably not. Best answer: try both and test it. Bestest answer: just use one and don't even care about it. – s3rius Mar 31 '13 at 19:59
5 Answers
queue
and stack
are both container adaptors, not complete containers in their own right.
Both stack
and queue
are implemented on top of a std::deque
by default, they should have similar performance if you did not change this setup.
It really depends on what kind of application you are coding and you may select the underlying container which benefits those operations you want the most.

- 23,276
- 10
- 49
- 62
Answer to your main question: I don't know. I don't think any of them is significantly faster, because for std::deque
(the default internal container for both stack and queue) the push_back and push_front (and pop_back and pop_front) are symmetric. None should be faster. I would however suggest using plain old std::vector with push_back
and pop_back
, or equivalently
std::stack<T, std::vector<T>>
See here for the reasons why stack uses deque by default.

- 1
- 1

- 130,161
- 59
- 324
- 434
they both have constant complexity ... you'll just need to time it to determine whether any of the constants is higher
http://www.cplusplus.com/reference/stack/stack/pop/
http://www.cplusplus.com/reference/queue/queue/pop/

- 5,057
- 4
- 32
- 43
While queue
and stack
aren't wildly different in performance, they obviously induce a different node-visiting order. One of them may give a more cache-friendly order than the other, depending on how your nodes are laid out in memory.

- 61,398
- 6
- 86
- 164
queue and stack are different. First is FIFO and stack is FILO

- 1,301
- 10
- 23
-
1
-
-
-
@aguyngueran Vector has a huge overhead because of the copying. It's not (usually) notable in client-side applications but it may have a huge performance impact in server-side and other specific applications. vector is not an all-around container. If you want to store a temporary list - vector is great. If you want to store temporary individual objects - it will impact the performance. – Pijusn Apr 25 '15 at 04:41