情景:有一个结构体指针存放若干同类结构体,现需要按照结构体中的某个元素进行排序~~~
Po下自己的测试代码:
#include <iostream>
#include<algorithm>
using namespace std;
struct CoordinateDistance
{
double x;
double distance;
};
void SortSmallToBig(CoordinateDistance* array, int size)
{
//get each point's distance error,then sort them from small to big
for (int i = 0; i < size; ++i)
{
for (int j = i + 1; j < size; ++j)
{
if ((array + i)->distance>(array + j)->distance)
{
CoordinateDistance temp = *(array + i);
*(array + i) = *(array + j);
*(array + j) = temp;
}
}
}
}
//from big to small
bool cmp1(const CoordinateDistance &a, const CoordinateDistance &b)
{
return a.distance > b.distance;
}
//from small to big
bool cmp2(const CoordinateDistance &a, const CoordinateDistance &b)
{
return a.distance < b.distance;
}
void main()
{
CoordinateDistance point[] = { { 1.0, 3.0 }, { 0.5, 4.0 }, {3.0,2.0}};
int size_point = sizeof(point) / sizeof(CoordinateDistance);
CoordinateDistance *p = point;
sort(p, p + size_point, cmp1);
//SortSmallToBig(p,size_point);
cout << "size" << size_point << endl;
}
其中,SortSmallToBig是自己写的升序函数,代码中还是用了STL中的sort函数。