Suppose we have the following task: we want to read a set of coordinates (x, y) and a name, and then sort them in order, increasing the distance from the origin (0, 0). Here is an algorithm that uses the simplest sorting of bubbles:
#include<iostream> #include <algorithm> using namespace std; struct point{ float x; float y; char name[20]; }; float dist(point p){ return px*p.x+py*py; } 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 an STL sorting algorithm instead of sorting bubbles. How to do it?
I mean, how should I use the dist function in the STL sort algorithm?
c ++
dato datuashvili
source share