简体   繁体   中英

Priority Queue Multimap Class with Multiple items of the same key value in C++

I am writing a c++ priority queue multi map class that is able to handle multiple items of the same key value. I have a push method that will create the items in the multimap, and a pop method that will return the item with the highest key value. I want to be able to add multiple items with the same key value. If two items have the same key value only one should be popped, and the other should remain in the queue.

Here is my code for the pop method.

    string PQ::pop()
   {
int maxKey = 0;
string maxValue;

if(pq.size() > 0)
{
    for(std::multimap<int, string>::iterator iter = pq.begin(); iter != pq.end(); iter++)
    {
        if(iter->first >= maxKey)
        {
            maxKey = iter->first;
            maxValue = iter->second;

        }
    }
}
else
{
    maxValue = "The queue is empty";
}
pq.erase(maxKey);
return maxValue;
    }

When I run this code in my main method:

    pq.push(1, "one");
    pq.push(3, "three");
    pq.push(3, "three2");
    pq.push(50, "fifty2");
    pq.push(50, "fifty");

    cout << pq.pop() << endl;
    cout << pq.pop() << endl;
    cout << pq.pop() << endl;
    cout << pq.pop() << endl;
    cout << pq.pop() << endl;

This is what is printed out:

fifty2 three one

When it should be:

fifty2 fifty three three2 one.

In short: pq.erase(maxKey) removes all elements with a key equal to maxKey - not just one element.

First pop() returns only fifty2 but removes both fifty2 and fifty , second pop() returns only three but removes both three and three2 , third pop() returns and removes one and fourth and fifth pop() s just return empty string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM