假设我们有以下问题 - 我们想要读取一组(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;
}
Run Code Online (Sandbox Code Playgroud)
但是我想写STL排序算法而不是冒泡排序.怎么办?
我的意思是,我应该如何在STL排序算法中使用dist函数?
STL排序函数std::sort可以将用户定义的比较函数(或函数对象)作为可选的第三个参数.所以如果你有你的物品,例如:
vector<point> points;
Run Code Online (Sandbox Code Playgroud)
你可以通过调用它们来排序它们
sort(points.begin(), points.end(), my_comp);
Run Code Online (Sandbox Code Playgroud)
哪个my_comp()是具有以下原型的函数:
bool my_comp(const point &a, const point &b)
Run Code Online (Sandbox Code Playgroud)