排序是一种很常用的算法,传统冒泡排序和基于递归的快速排序都很经典。一般理解的排序就是对单一数值的排序,比如对年龄的排序和对身高的排序。然而,实际业务应用中的排序往往是复杂的,可能是二维或者三维空间点的排序,甚至是一个抽象复杂的结构体或者类对象的排序。但是,万变不离其宗,只要我们明确了排序的准则,不管多复杂的结构体都可以通过系统自带的sort函数来处理。下面以二维图像中,点的排序为例进行演示,排序准则就是距离图像中心点的距离。
一、代码部分
这里考虑了C风格的数组和C++风格的数组,分别进行演示。
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm> //用sort函数必包含
using namespace std;
struct Point
{
double x;
double y;
};
Point centerPoint; //中心点
double CalDistance(Point p1, Point p2)
{
double d = sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
return d;
}
bool ComparePoint(const Point& a, const Point& b)
{
double d1 = CalDistance(centerPoint, a);
double d2 = CalDistance(centerPoint, b);
if (d1 < d2)
{
return true;
}
else
{
return false;
}
}
int main()
{
//假设图像尺寸是1000*1000
centerPoint = { 500,500 };
Point points[5] = { {765.4,77.89},{123,34},{44,24},{578.3,89},{566.9,35.7} }; //C风格
vector<Point> vecPoint = { {765.4,77.89},{123,34},{44,24},{578.3,89},{566.9,35.7} }; //C++风格
Point p1, p2, p3;
//关键点,三个参数分别是起点、终端、函数名
sort(points, points + 5, ComparePoint); //C风格
sort(vecPoint.begin(), vecPoint.end(), ComparePoint); //C++风格
cout << "C style:" << endl;
for (int i = 0; i < 5; i++)
{
cout << "x=" << points[i].x << ", y=" << points[i].y << endl;
double d = CalDistance(centerPoint, points[i]);
cout << "distance=" << d << endl;
cout << endl;
}
cout << "C++ style:" << endl;
for (int i = 0; i < vecPoint.size(); i++)
{
cout << "x=" << vecPoint[i].x << ", y=" << vecPoint[i].y << endl;
double d = CalDistance(centerPoint, vecPoint[i]);
cout << "distance=" << d << endl;
cout << endl;
}
return(0);
}
二、结果展示
可以看到,二维点按照距离中心点自近到远的顺序进行了排序。