gpt4 book ai didi

c++ - partial_sort 和智能指针

转载 作者:行者123 更新时间:2023-11-28 06:56:29 25 4
gpt4 key购买 nike

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

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

最佳答案

传递给 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));

关于c++ - partial_sort 和智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23115138/

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