找到距离原点最近的位置
问题描述:
假设我们有以下问题 - 我们想要读取一组(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函数?
答
STL排序功能std::sort
可以将用户定义的比较函数(或函数对象)作为可选的第三个参数。所以,如果你有例如,您的项目:
vector<point> points;
你可以通过调用对它们进行排序:
sort(points.begin(), points.end(), my_comp);
其中my_comp()
与原型如下功能:
bool my_comp(const point &a, const point &b)
答
#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);
+ 1。如果'point'很大,让'my_sort()'把const引用指向'point'而不是复制这些对象可能会更有效率。 – 2010-08-26 21:55:03
好的电话。相应地更新答案。 – 2010-08-26 22:01:29