How do I clear the std::queue efficiently?

后端 未结 11 971
醉梦人生
醉梦人生 2020-12-12 09:10

I am using std::queue for implementing JobQueue class. ( Basically this class process each job in FIFO manner). In one scenario, I want to clear the queue in one shot( delet

11条回答
  •  我在风中等你
    2020-12-12 09:38

    Another option is to use a simple hack to get the underlying container std::queue::c and call clear on it. This member must be present in std::queue as per the standard, but is unfortunately protected. The hack here was taken from this answer.

    #include 
    
    template
    typename ADAPTER::container_type& get_container(ADAPTER& a)
    {
        struct hack : ADAPTER
        {
            static typename ADAPTER::container_type& get(ADAPTER& a)
            {
                return a .* &hack::c;
            }
        };
        return hack::get(a);
    }
    
    template
    void clear(std::queue& q)
    {
        get_container(q).clear();
    }
    
    #include 
    int main()
    {
        std::queue q;
        q.push(3);
        q.push(5);
        std::cout << q.size() << '\n';
        clear(q);
        std::cout << q.size() << '\n';
    }
    

提交回复
热议问题