gpt4 book ai didi

c++ - 如何遍历包含 deque 元素的斐波那契堆( boost )

转载 作者:太空狗 更新时间:2023-10-29 23:16:58 26 4
gpt4 key购买 nike

我正在使用 Fibonacci heap(boost) 对元素数组进行排序,但我无法遍历堆。代码是这样的:

#include <deque>
#include <boost/heap/fibonacci_heap.hpp>
#include <iostream>

struct MyData {
...
long int id;

...
};

struct MyCompare{
bool operator()(const deque<MyData> &a, const deque<MyData> &b) const
{
return a[a.size()-1].id > b[b.size()-1].id;
}
};


int main()
{ deque<MyData> array1;
deque<MyData> array2;

MyData app;
app.id=15;
array1.push_front(app);
app.id=10;
array1.push_front(app);

app.id=5;
array2.push_front(app);
app.id=2;
array2.push_front(app);

boost::heap::fibonacci_heap<deque<MyData>, boost::heap::compare<MyCompare> > fib_heap;
fib_heap.push(array1);
fib_heap.push(array2);
boost::heap::fibonacci_heap<deque<MyData>, boost::heap::compare<MyCompare> >::iterator it;
boost::heap::fibonacci_heap<deque<MyData>, boost::heap::compare<MyCompare> >::iterator beg =fib_heap.begin();
boost::heap::fibonacci_heap<deque<MyData>, boost::heap::compare<MyCompare> >::iterator end =fib_heap.end();

for (it=beg;it!=end; ++it) {
deque<MyData> elem;
elem =*it;
for (int k=0;k < elem.size();k++)
cout<<" "<<elem[k].id;
cout<<"\n";
}


}

它在“elem = *it”这一行给我这个错误:recursive_tree_iterator 的实例化错误: 递归树迭代器(无效): 适配器类型(0) {}

有什么办法吗?或者使用另一个有序堆而不是 Fibonacci?非常感谢。

最佳答案

我认为错误是您不能默认构造迭代器。尝试消除 it 变量的创建并将其移动到 for 循环中:

boost::heap::fibonacci_heap<deque<MyData>, boost::heap::compare<MyCompare> >::iterator beg =fib_heap.begin();
boost::heap::fibonacci_heap<deque<MyData>, boost::heap::compare<MyCompare> >::iterator end =fib_heap.end();

for (boost::heap::fibonacci_heap<deque<MyData>, boost::heap::compare<MyCompare> >::iterator it=beg;it!=end; ++it) {
deque<MyData> elem;
elem =*it;
for (size_t k=0;k < elem.size();k++)
cout<<" "<<elem[k].id;
cout<<"\n";
}

为了按堆顺序迭代,你可以使用:

ordered_iterator ordered_begin(void) const;
ordered_iterator ordered_end(void) const;

此外,我认为使用 auto 关键字会对代码有益:

for (auto it=fib_heap.begin(), end=fib_heap.end();it!=end; ++it) {
deque<MyData> elem;
elem =*it;
for (size_t k=0;k < elem.size();k++)
cout<<" "<<elem[k].id;
cout<<"\n";
}

关于c++ - 如何遍历包含 deque<MyData> 元素的斐波那契堆( boost ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21110381/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com