C++ STL make_heap 和 pop_heap 不工作
我需要使用堆,所以我搜索了STL,但它似乎不起作用,我写了一些代码来解释我的意思:
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
struct data
{
int indice;
int tamanho;
};
bool comparator2(const data* a, const data* b)
{
return (a->tamanho < b->tamanho);
}
int main()
{
std::vector<data*> mesas;
data x1, x2, x3, x4, x5;
x1.indice = 1;
x1.tamanho = 3;
x2.indice = 2;
x2.tamanho = 5;
x3.indice = 3;
x3.tamanho = 2;
x4.indice = 4;
x4.tamanho = 6;
x5.indice = 5;
x5.tamanho = 4;
mesas.push_back(&x1);
mesas.push_back(&x2);
mesas.push_back(&x3);
mesas.push_back(&x4);
mesas.push_back(&x5);
make_heap(mesas.begin(), mesas.end(), comparator2);
for(int i = 0 ; i < 5 ; i++)
{
data* mesa = mesas.front();
pop_heap(mesas.begin(),mesas.end());
mesas.pop_back();
printf("%d, %d\n", mesa->indice, mesa->tamanho);
}
return 0;
};
这就是我得到的:
4, 6
2, 5
1, 3
3, 2
5, 4
所以它不能作为堆工作,因为向量上的最大元素没有正确返回。
或者我做错了什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要将
comparator2
传递给std::pop_heap
,因为这就是您创建堆的方式。否则,它将使用指针的默认小于运算符,该运算符仅比较指针值。You need to pass
comparator2
tostd::pop_heap
since that is how you created the heap. Otherwise, it will use the default less than operator for pointers, which simply compares the pointer values.MSN的回答是正确的。但是,以下任一样式指南都可以防止此错误:
声明比较器适用于引用,而不是对象,如
操作符<
那样。使用对象的向量
,而不是指针。您可能确实需要指针向量,在这种情况下,这不适用。
使用
std::priority_queue
(来自
),它将pop_heap
和pop_back
联系在一起为了你,记住你的比较器。这需要一个函子比较器:最优雅的方法是使其成为
数据
的默认比较:priority_queue
还可以采用预填充的未排序容器,并将复制该容器。MSN's answer is correct. However, either of a couple style guidelines can prevent this error:
Declare the comparator to work on references, not objects, as
operator<
would. Use avector
of objects, not pointers.You might really need the vector of pointers, in which case this doesn't apply.
Use
std::priority_queue
(from<queue>
), which ties togetherpop_heap
andpop_back
for you, remembering your comparator. This requires a functor comparator:Most elegant way is to make this the default comparison for
data
:priority_queue
can also take a prefilled unsorted container, which it will copy.std::set 怎么样
What about std::set
我有一个类似的问题,并且能够用这样的方法解决它:
I had a similar problem and was able to solve it with something like this: