C++ STL Vector 两种常用排序方法(笔记)
目前有一个vector< Point > totalPoint 存储有从Point类型坐标点的向量,由于Point从Mat图像中获取时是乱序,现在需要按Point类型中的x从小到大进行排序
方法一:使用冒泡排序法进行排序(其他排序算法也同样适用)
先参考冒泡排序法
BubbleSort(int Arry[],int lenth)
{
int temp;
for(int i=0;i<lenth-1;i++)
for(int j=0;j<lenth-i-1;j++)
if(Arry[j]>Arry[j+1])
{
temp=Arry[j];
Arry[j]=Arry[j+1];
Arry[j+1]=temp;
}
}
vector声明
vector<Point> totalPoint;
按Point类型中x坐标从小到大进行排序 ( totalPoint[ j ].x )
写出vector排序法
for (int i = 0; i < totalPoint.size(); i++)//冒泡排序
{
for (int j = 0; j < totalPoint.size() - i - 1; j++)
{
if (totalPoint[j].x > totalPoint[j + 1].x)
{
tempP = totalPoint[j];
totalPoint[j] = totalPoint[j + 1];
totalPoint[j + 1] = tempP;
}
}
}
for (int i = 0; i < totalPoint.size(); i++)//打印
{
cout << "x = " << totalPoint[i].x << " , " << "y = " << totalPoint[i].y << endl;
}
方法二:sort函数排序法
sort函数为c++标准库中的函数,头文件为#include< algorithm >
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
首先定义一个cmp函数规定排序方法(按Point类型中x坐标从小到大进行排序,如果参数不写,而vector中的类型又是结构体或类,很可能会报错)
cmp函数
bool cmp(Point p1, Point p2) {
//按x从小到大排序
if (p1.x != p2.x)
return p1.x < p2.x;
}
排序
sort(totalPoint.begin(), totalPoint.end(), cmp);//排序
for (vector<Point>::iterator iter = totalPoint.begin(); iter != totalPoint.end(); iter++)//使用迭代器访问并打印内容
{
cout << "x,y = " << *iter << endl;//iter相当于指针
}