我正在使用 C++ STL 堆算法,并且围绕它编写了一个包装器类,这样我就可以做一些其他的事情。例如,当我尝试使用下面的代码时:
//! Min-heap wrapper class.
class FMMHeap{
public:
FMMHeap(Vector &phi) : _phi(phi) {}
bool operator()(unsigned p1, unsigned p2) {return fabs(_phi(p1)) > fabs(_phi(p2)); }
inline void pop(){ pop_heap(_heap.begin(),_heap.end(),*this); _heap.pop_back(); }
[...lots of other stuff...]
vectorU32 _heap;
Vector &_phi;
}
这比我有一个像这样的单独函数对象时慢了 wayyyyy:
struct HeapSort{
public:
HeapSort(Vector &phi) : _phi(phi) {}
bool operator()(unsigned p1, unsigned p2) {return fabs(_phi(p1)) > fabs(_phi(p2)); }
private:
Vector &_phi;
};
class FMMHeap{
public:
FMMHeap(Vector &phi) : cmp(phi) {}
inline void pop(){ pop_heap(_heap.begin(),_heap.end(),cmp); _heap.pop_back(); }
[...lots of other stuff...]
vectorU32 _heap;
HeapSort cmp;
}
我不确定这是为什么。减速是否来自 *this 因为该类有大量数据?这似乎很奇怪。还是与函数对象的使用方式有关?
我不确定:但也许 pop_heap
最终会复制您传入的仿函数对象。FMMHeap
的拷贝比简单的 HeapSort
更昂贵
我是一名优秀的程序员,十分优秀!