0
我正在写一个C++优先级队列多地图类,它能够处理同一个键值的多个项目。我有一个将在multimap中创建项目的push方法,以及一个将返回具有最高键值的项目的pop方法。我希望能够使用相同的键值添加多个项目。如果两个项目具有相同的键值,则只应该弹出一个项目,而另一个项目应保留在队列中。优先级队列Multimap类与C++中的多个相同的键值
这是我的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 一个
当它应该是:
fifty2 五十个 三个 three2 one。