[英]Sorting a list with struct pair using std::sort
我想排序一個結構列表,一個迭代器和double值的對結構;
以上是我的嘗試。 我的結構是
template<class Iterator>
struct Pair{
double distance;
Iterator iterator; };
我的分類功能是:
template<class SetIterator>
static bool MyDataSortPredicate(const Pair<SetIterator>& lhs, const Pair<SetIterator>& rhs){
return lhs.distance < rhs.distance;
}
創建結構值列表; 它是distance_pair,請注意其類型。
template<class SetIterator>
std::vector<Pair<SetIterator> > createSortedPointDistancePairs(
SetIterator begin, SetIterator end,Vector const& query ){
std::vector<double> it(std::distance(begin,end));
std::vector<double>::iterator iter;
std::vector<Pair<SetIterator> > distance_pair(std::distance(begin,end)); //to make space
computeDistances(begin, end, query, it.begin());
SetIterator pos = begin;
int i = 0;
for(iter = it.begin(); iter!=it.end();++iter,i++){
if (pos!=end){
Pair<SetIterator> set;
set.distance = *iter;
set.iterator = pos;
distance_pair[i] = set;
}
++pos;
}
現在,我使用比較函數MyDataSortPredicate來創建一個排序的結構列表,其中距離的順序在值中進行排序,
std::sort(distance_pair.begin(),distance_pair.end(),MyDataSortPredicate);
錯誤是:
error: no matching function for call to 'sort'
std::sort(distance_pair.begin(),distance_pair.end(),MyDataSortPredicate);
^~~~~~~~~
main_test.cpp:51:2: note: in instantiation of function template specialization
'createSortedPointDistancePairs<std::__1::__wrap_iter<Vector *> >' requested here
createSortedPointDistancePairs( vector_contains.begin(), vector_contains.end(), query);
還有更多文字。
MyDataSortPredicate
不是具體的對象或函數。 它是一個功能模板。 因此,它不能作為參數傳遞給函數。 您需要使用模板參數實例化它。
std::sort(distance_pair.begin(),distance_pair.end(),MyDataSortPredicate<SomeType>);
如果您不想為比較器顯式提供類型,則可以制作一個多態函數對象,如std::less<void>
:
struct MyDataSortPredicate
{
template <typename SetIterator>
bool operator(const Pair<SetIterator>& lhs, const Pair<SetIterator>& rhs)
{
return lhs.distance < rhs.distance;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.