【发布时间】:2011-03-28 02:01:01
【问题描述】:
我想使用具有自定义数据类型和几个比较标准的 std::priority_queue 容器(我为它们中的每一个定义了一个仿函数;它们中的每一个都在处理相同的类型)。 使用的比较标准本身应该可以通过函数参数进行配置(避免队列的 if_then_ 初始化)。
基于this post,据我所知,使用比较函子,它本身是用指向已定义比较函数之一的函数指针初始化的,我尝试使用可配置的比较函子,它用另一个比较函子初始化(然后存储在本地并在调用时使用)。我还没有让它工作。
我什至不知道是否可以做我想做的事情。我不知道我是否在类型方面做错了(我使用了 typedef boost::function xxx)或需要额外的 C++0x 功能(“闭包”有帮助吗?)。
所以基本上我希望有类似以下的工作(这不会编译一个非长但丑陋的错误;GCC 4.5):
#include <iostream>
#include <queue>
#include <boost/tuple/tuple.hpp>
#include <boost/function.hpp>
typedef boost::tuple<double, int> custom_type; // example only!
typedef boost::function<bool (const custom_type & l, const custom_type & r)> comp_type; // comparison functor
struct fifo_comp
{
bool operator() (const custom_type & l, const custom_type & r) const
{
// compare only id
return l.get<1>() > r.get<1>();
}
};
struct lifo_comp
{
bool operator() (const custom_type & l, const custom_type & r)
{
// compare only id
return l.get<1>() < r.get<1>();
}
};
class Compare
{
public:
explicit Compare(const comp_type & comp);
bool operator() (const custom_type & l, const custom_type & r)
{
return comp(l, r);
}
private:
const comp_type & comp;
};
class Some_Class_Using_Queue
{
public:
Some_Class_Using_Queue(comp_type & comp) : pqueue(Compare(comp)) {}
void test()
{
pqueue.push(custom_type(1.0, 1));
}
private:
std::priority_queue<custom_type, std::vector<custom_type>, Compare> pqueue;
};
int main()
{
comp_type f = fifo_comp();
Some_Class_Using_Queue temp((f)); // critical
temp.test();
return 1;
}
- 任何帮助让它为我工作(鼓励使用 STL/Boost)?
- 有更好的想法(完全不同)吗?
- 这里有什么很酷的 C++0x 功能可以提供帮助(可能是闭包)?
谢谢。
PS/Edit:我知道,使类模板化并使用适当的 comp-class 作为模板参数调用类是可能的并且非常容易。但我不知道这是否是更好的方法(关于设计)。使用这种方法,我必须在调用之前切换/if-else,因为模板参数需要在编译时可用。
PS:我设置了“priority_queue”标签,即使问题可能完全独立于这个适配器类。如果有人想删除它,那就去做吧。
【问题讨论】:
标签: c++ boost stl c++11 priority-queue