C/C++对结构体的排序——以二维坐标点排序为例

       排序是一种很常用的算法,传统冒泡排序和基于递归的快速排序都很经典。一般理解的排序就是对单一数值的排序,比如对年龄的排序和对身高的排序。然而,实际业务应用中的排序往往是复杂的,可能是二维或者三维空间点的排序,甚至是一个抽象复杂的结构体或者类对象的排序。但是,万变不离其宗,只要我们明确了排序的准则,不管多复杂的结构体都可以通过系统自带的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);
}

二、结果展示

可以看到,二维点按照距离中心点自近到远的顺序进行了排序。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值