简体   繁体   中英

Sorting a list with struct pair using std::sort

I want to sort a struct list, a pair struct of a iterator and double value;

The above is my attempt. My struct is

    template<class Iterator>
struct Pair{
    double distance; 
    Iterator iterator; };

My sorting fucntion is;

template<class SetIterator>
        static bool MyDataSortPredicate(const Pair<SetIterator>& lhs, const Pair<SetIterator>& rhs){
            return lhs.distance < rhs.distance;
        }

Creating list of struct values; it is distance_pair, notice its type.

 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;
    }

Now my attemt to make a sorted struct list, where the order of distance is accending in values, using my compare function MyDataSortPredicate,

std::sort(distance_pair.begin(),distance_pair.end(),MyDataSortPredicate);

The error is:

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

And quite more text.

MyDataSortPredicate is not a concrete object or function. It is a function template. As such, it cannot be passed as an argument to a function. You need to instantiate it with a template argument.

std::sort(distance_pair.begin(),distance_pair.end(),MyDataSortPredicate<SomeType>);

If you do not want to explicitely provide type for comparator, you can make a polymorfic function object like std::less<void> :

struct MyDataSortPredicate
{
    template <typename SetIterator> 
    bool operator(const Pair<SetIterator>& lhs, const Pair<SetIterator>& rhs)
    {
        return lhs.distance < rhs.distance;
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM