partial_sort和智能指针

时间:2014-04-16 16:31:35

标签: c++ sorting boost smart-pointers

我有一个SetPartitionVector类,派生自vector<SetPartition>。我想使用自定义比较函数partial_sort这个向量,但编译时出错。

bool ScalableSummary::featuresDistComp(SetPartition cluster1, SetPartition cluster2){
    return (segmentClusters.AverageSOD(cluster1) > segmentClusters.AverageSOD(cluster2));
}

void ScalableSummary::selectLeastConsensualFeatures(const int p){
    partial_sort(segmentClusters.begin(), segmentClusters.begin() + p, segmentClusters.end(), featuresDistComp);
}

segmentClustersScalableSummary SetPartitionVector类型的成员,以这种方式填充:

SetPartition_ptr cluster;
...
segmentClusters.push_back(*cluster);

SetPartition_ptr是一个智能指针,定义如下: typedef boost::shared_ptr<SetPartition> SetPartition_ptr;

这是我从编译器得到的错误:

g++ -o ScalableSummary.o -c ScalableSummary.cpp -Iinclude -Wall -g
ScalableSummary.cpp: In member function ‘void ScalableSummary::selectLeastConsensualFeatures(int)’:
ScalableSummary.cpp:56:108: erreur: no matching function for call to ‘partial_sort(std::vector<SetPartition>::iterator, __gnu_cxx::__normal_iterator<SetPartition*, std::vector<SetPartition> >, std::vector<SetPartition>::iterator, <unresolved overloaded function type>)’
ScalableSummary.cpp:56:108: note: candidates are:
/usr/include/c++/4.6/bits/stl_algo.h:5240:5: note: template<class _RAIter> void std::partial_sort(_RAIter, _RAIter, _RAIter)
/usr/include/c++/4.6/bits/stl_algo.h:5279:5: note: void std::partial_sort(_RAIter, _RAIter, _RAIter, _Compare) [with _RAIter = __gnu_cxx::__normal_iterator<SetPartition*, std::vector<SetPartition> >, _Compare = bool (ScalableSummary::*)(SetPartition, SetPartition)]
/usr/include/c++/4.6/bits/stl_algo.h:5279:5: note:   no known conversion for argument 4 from ‘<unresolved overloaded function type>’ to ‘bool (ScalableSummary::*)(SetPartition, SetPartition)’

1 个答案:

答案 0 :(得分:1)

传递给std::partial_sort的函数对象需要是可调用对象或函数指针。要创建一个函数指针,你需要使用地址运算符&,就像从任何其他变量中指出一样:

partial_sort(..., &featuresDistComp);
//                ^
//                |
// Note address-of operator here

另外,我希望您的功能标记为static?您不能将非静态成员函数用作普通函数指针。原因是所有非静态成员函数都有一个隐藏的第一个参数,即函数内的this指针。因此要么确保函数是static,要么使用例如using namespace std::placeholders; // for _1, _2, _3... partial_sort(..., std::bind(&ScalableSummary::featuresDistComp, this, _1, _2)); std::bind

{{1}}