c++中具有相同键值的多个项的优先队列Multimap类

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

本文关键字:优先队列 Multimap 键值 c++      更新时间:2023-10-16

我正在编写一个c++优先队列多映射类,能够处理相同键值的多个项目。我有一个push方法,它将在multimap中创建项目,还有一个pop方法,它将返回具有最高键值的项目。我希望能够添加多个项目具有相同的键值。如果两个项具有相同的键值,则只应弹出其中一个,而另一个应保留在队列中。

下面是pop方法的代码。

    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;
    }

当我在主方法中运行这段代码时:

    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;

打印出来的内容:

fifty2三个1

应该是:

fifty2五十三个three2一。

简而言之:pq.erase(maxKey)删除所有键值等于maxKey元素,而不仅仅是一个元素。

第一个pop()只返回fifty2,但删除fifty2fifty,第二个pop()只返回three,但删除threethree2,第三个pop()返回并删除one,第四和第五个pop()返回空字符串。