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函數?
+ 1。如果'point'很大,讓'my_sort()'把const引用指向'point'而不是複製這些對象可能會更有效率。 – 2010-08-26 21:55:03
好的電話。相應地更新答案。 – 2010-08-26 22:01:29