C++利用sort函數對自訂型態排序

#include <algorithm>
#include <functional>
#include <deque>
#include <iostream>

using namespace std;

typedef struct
{
    int idx_N;
    double dist_N;
} Nebor_heap;

namespace std
{
template<>
struct greater<Nebor_heap>: binary_function <Nebor_heap, Nebor_heap, bool>
{
  bool operator () (const Nebor_heap& s1, const Nebor_heap& s2) const
  {
       return s1.dist_N>s2.dist_N;
  }
};

template<>
struct less<Nebor_heap>: binary_function <Nebor_heap, Nebor_heap, bool>
{
  bool operator () (const Nebor_heap& s1, const Nebor_heap& s2) const
  {
    return s1.dist_N<s2.dist_N;
  }
};
}; // end namespace std

/*
struct cmp_greater : binary_function <Nebor_heap,Nebor_heap,bool>
{
  bool operator() (const Nebor_heap& s1, const Nebor_heap& s2) const
  {
    return s1.dist_N>s2.dist_N;
  }
};
*/

int main()
{
    Nebor_heap a[] =  {{1, 10.1}, {2, 2.0}, {3, 4.0}, {4 , 55}};
    
    deque<Nebor_heap> q1(a, a+(sizeof(a)/sizeof(Nebor_heap)));

    for (int i=0 ; i<q1.size() ; ++i)
        cout << "idx=" << q1[i].idx_N << " dist=" << q1[i].dist_N <endl;
    
    cout << endl << "sorting...." << endl << endl;
    sort(q1.begin(), q1.end(), greater<Nebor_heap>());
    
    for (int i=0 ; i<q1.size() ; ++i)
        cout << "idx=" << q1[i].idx_N << " dist=" << q1[i].dist_N <endl;

    cout << endl << "sorting...." << endl << endl;
    sort(q1.begin(), q1.end(), less<Nebor_heap>());
    
    for (int i=0 ; i<q1.size() ; ++i)
        cout << "idx=" << q1[i].idx_N << " dist=" << q1[i].dist_N <endl;
    
    return 0;
}

留言