Queue with unique entries in c++

后端 未结 4 887
生来不讨喜
生来不讨喜 2021-02-05 07:25

I need to implement a queue containing unique entries(no duplicates) in C or C++. I am thinking of maintaining a reference of elements already available in queue but that seems

4条回答
  •  灰色年华
    2021-02-05 08:06

    How about an auxiliary data structure to track uniqueness:

    std::queue q;
    std::set> s;
    
    // to add:
    
    void add(Foo const & x)
    {
        if (s.find(x) == s.end())
        {
            q.push_back(x);
            s.insert(std::ref(q.back()));  // or "s.emplace(q.back());"
        }
    }
    

    Or, alternatively, reverse the roles of the queue and the set:

    std::set s;
    std::queue> q;
    
    void add(Foo const & x)
    {
        auto p = s.insert(x);       // std::pair::iterator, bool>
        if (s.second)
        {
            q.push_back(std::ref(*s.first));  // or "q.emplace_back(*s.first);"
        }
    }
    

提交回复
热议问题