The std::queue
class is unclear as to the complexity of the size
member function. It appears to be based on the data structure implementation used at the time.
One would assume that size
would be O(C)
, but it's totally possible for it to be O(N)
. Obviously, I can keep my own size, but I would rather just call size
.
(Question modified): since deque
is the default container, what is O ( ) of std::deque::size()?
At least since C++11, the complexity of std::queue::size
is constant: O(1).
This is guaranteed by the fact that the underlying container of std::queue
, as per §23.6.3.1/1, have to fit the requirements of SequenceContainer
, that inherits the requirement of Container
, which, in turn, as per §23.2.1, requires the member function size
to have a constant time complexity.
To sum up the very good answers here:
O(1)
(@Jeffrey)O(1)
, but at least O(C)
. (@juanchopanza)Thus, if you need to ensure O(1)-ness of size() in C++98, you must keep your own count.
If I might, I would like to step on my soap box and thank the C++11 group for closing this horrendous specification hole. Many languages/libraries (such as Scala) take great pains to define the BIG-O of an operator. Given that the main use case of C++ is performance, I find this lack of specification amazing. It is completely unacceptable that one should have to inspect header code to determine performance characteristics of std classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With