从原点找到最近的位置

时间:2010-08-26 21:45:21

标签: c++

假设我们有以下问题 - 我们想要读取一组(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函数?

2 个答案:

答案 0 :(得分: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 :(得分: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);
相关问题