2010-08-26 110 views
7

假設我們有以下問題 - 我們想要讀取一組(x,y)座標和名稱,然後按順序對它們進行排序,方法是增加距原點的距離(0,0 )。這裏是一個最簡單的使用冒泡排序的算法:找到距離原點最近的位置

#include<iostream> 
    #include <algorithm> 
    using namespace std; 
    struct point{ 
     float x; 
     float y; 
     char name[20]; 

     }; 
     float dist(point p){ 
      return p.x*p.x+p.y*p.y; 
      } 
     void sorting(point pt[],int n){ 
      bool doMore = true; 
     while (doMore) { 
      doMore = false; // Assume no more passes unless exchange made. 
      for (int i=0; i<n-1; i++) { 
       if (dist(pt[i]) > dist(pt[i+1])) { 
        // Exchange elements 
        point temp = pt[i]; pt[i] = pt[i+1]; pt[i+1] = temp; 
        doMore = true; // Exchange requires another pass. 
       } 
      } 
     } 

     } 
     void display(point pt[],int n){ 
      for (int i=0;i<n;i++){ 
       cout<<pt[i].name<< " "; 
        } 
     } 
    int main(){ 
    point pts[1000]; 
    int n=0; 

    while (cin>>pts[n].name>>pts[n].x>>pts[n].y){ 
     n++; 

    } 
    sorting(pts,n); 
    display(pts,n); 

    return 0; 
    } 

但我想寫STL排序算法,而不是冒泡排序。如何做?

我的意思是,我應該如何在STL排序算法中使用dist函數?

回答

8

STL排序功能std::sort可以將用戶定義的比較函數(或函數對象)作爲可選的第三個參數。所以,如果你有例如,您的項目:

vector<point> points; 

你可以通過調用對它們進行排序:

sort(points.begin(), points.end(), my_comp); 

其中my_comp()與原型如下功能:

bool my_comp(const point &a, const point &b) 
+1

+ 1。如果'point'很大,讓'my_sort()'把const引用指向'point'而不是複製這些對象可能會更有效率。 – 2010-08-26 21:55:03

+0

好的電話。相應地更新答案。 – 2010-08-26 22:01:29

2
#include <algorithm> 

bool sort_by_dist(point const& p1, point const& p2) { 
    return dist(p1) < dist(p2); 
} 

... 

std::sort(pt, pt + n, sort_by_dist);