tags:

views:

84

answers:

2

Suppose we have the following problem. We want to read a set of (x, y) coordinates and a name, then sort them in order increasing distance from the origin (0, 0).here is algorithm which use simplest buble sort

 #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;
    }

but i want to write STL sorting algorithm instead of buble sort and how to do such?i mean that how use dist function in STL sort algorithm thanks

+8  A: 

The STL sort function std::sort can take a user-defined comparison function (or function object) as an optional third argument. So if you have your items in e.g.:

vector<point> points;

You can sort them by calling:

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

where my_comp() is a function with the following prototype:

bool my_comp(const point &a, const point &b)
Oli Charlesworth
+1. If `point` is big, it may be more efficient to have `my_sort()` take const references to `point` instead of copying the objects.
j_random_hacker
Good call. Answer updated accordingly.
Oli Charlesworth
+2  A: 
#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);
j_random_hacker