我正在尝试编写优先级队列/堆实现,它允许迭代,删除元素,在迭代期间更改键和值,以及查找具有特定键的所有元素。 std::priority_queue
不支持迭代,boost::heap
不支持迭代期间对键和值的更改。我也尝试使用std::multimap
,但在迭代期间更改值也存在问题。
我的队列存储为std::vector
std::pairs<double, T>
。我认为我可以使用std::sort
和std::equal_range
函数而不定义我自己的比较器,因为std::pair
automatically overloads the <
operator。此外,this question建议使用带有容器对的std::equal_range
,但是我为std::equal_range
收到以下编译器错误。
'bool std::operator <(const std::vector<_Ty,_Ax> &,const std::vector<_Ty,_Ax> &)' : could not deduce template argument for 'const std::vector<_Ty,_Ax> &' from 'const double'
和
binary '<' : no global operator found which takes type 'std::pair<_Ty1,_Ty2>' (or there is no acceptable conversion)
我的猜测是这与使用模板有关,但在这种情况下,我还希望std::sort
失败。
为什么std::pair
<
的自动重载不适用于std::equal_range
?
我是否需要为优先级队列定义比较器?
测试
int main()
{
PriorityQueue<double> queue;
queue.push(1, 1);
queue.remove(0);
queue.cleanup(); //This call throws the error when it calls std::equal_range
}
标题
#include <vector>
#include <utility>
#include <algorithm>
template<typename T>
class PriorityQueue
{
T item;
typedef typename std::vector<std::pair<double, T>>::iterator It;
private:
std::vector<std::pair<double, T>> queue;
bool isSorted;
bool hasRemoved;
void sort(){
std::sort(queue.begin(), queue.end());
};
public:
PriorityQueue():isSorted(true), hasRemoved(false){};
void push(double cost, T val)
{
isSorted = false;
queue.push_back(std::make_pair(cost, val));
};
void remove(int i)
{
hasRemoved = true;
isSorted = false;
queue[i].first = DBL_MAX; //Pushes element to end of list
};
void cleanup()
{
if(!isSorted) sort();
if(hasRemoved)
{
std::pair<It, It> remove = std::equal_range(queue.begin(), queue.end(), DBL_MAX); // This line throws the error
queue.erase(remove.first, remove.second);
}
};
};
答案 0 :(得分:0)
错误在于您提供了一对对象列表,比如{{0,1},{1,2},{2,3}...}
,并且要求查找等于(例如)2
的值范围。编译器不知道如何比较pair<double,double>
和double
。