std::queue >::size() is slow in O(n)?

后端 未结 3 2084
你的背包
你的背包 2021-01-12 12:08

I experienced unexpected performance behavior of my code which uses a queue. I realized that performance degraded when more elements were in the queue. It turned out that us

相关标签:
3条回答
  • 2021-01-12 12:44

    queue is a container adaptor, so you have to understand that the complexity descriptions may refer only to the work the adaptor does itself (which is indeed constant, namely just passing the call through to the underlying container).

    For example, see this reference: size() calls the underlying container's size() function. For a list, this has complexity O(n) in C++98/03, and O(1) in C++11.

    0 讨论(0)
  • 2021-01-12 12:52

    Adding to Michael's answer: You're using std::list as your queue container, so the size() method depends on your std::list implementation of size. If you look up on the same website, you find http://www.cplusplus.com/reference/stl/list/size/ and the complexity is constant on some implementations and linear on others. If you need constant insertion and size, then you need a different data structure or a better std::list implementation.

    0 讨论(0)
  • 2021-01-12 12:54

    You're your queue to use a list container, instead of the deque default:

    typedef std::queue<QueueElementType, std::list<QueueElementType> > QueueType;
    

    You shouldn't be surprised that size takes O(n), since that's a perfectly valid implementation of the list container pre C++11. The previous version of the standard did not guarantee the complexity of the size member function for lists.

    If you change your code to:

    typedef std::queue<QueueElementType, std::deque<QueueElementType> > QueueType;
    

    You will see the behavior you want (O(1) size complexity).

    0 讨论(0)
提交回复
热议问题