partial_sort和智能指针

partial_sort and smart pointers

本文关键字:智能 指针 sort partial      更新时间:2023-10-16

我有一个从vector<SetPartition>派生的SetPartitionVector类。我想使用自定义比较函数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);
}

segmentClustersSetPartitionVector类型的ScalableSummary的成员,以这种方式填充:

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)’

传递给std::partial_sort的函数对象需要是可调用对象,或者是函数指针。要制作函数指针,您必须使用运算符&的地址,就像用任何其他变量制作指针一样:

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

另外,我希望您的函数标记为static?不能将非静态成员函数用作普通函数指针。原因是所有非静态成员函数都有一个隐藏的第一个参数,即函数内部的this指针。因此,要么确保函数为static,要么使用例如std::bind:

using namespace std::placeholders;  // for _1, _2, _3...
partial_sort(..., std::bind(&ScalableSummary::featuresDistComp, this, _1, _2));