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

后端 未结 3 2110
你的背包
你的背包 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条回答
  •  猫巷女王i
    2021-01-12 12:54

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

    typedef std::queue > 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 > QueueType;
    

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

提交回复
热议问题