To sum up the very good answers here:
- C++11:
O(1)
(@Jeffrey)
- C++98: unenforced, need to do experimentation based on the container class
- C++98 with default container: the default container for std::queue
is std::deque, which calculates size by subtracting two
iterators, which is not
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.