std::sort因为函数参数不明确,所以无法推导出模板参数等.
实验结果
本次实验是基于这样一个问题的:有一些坐标点集合(2d的坐标点,坐标点之间没有重复),每个坐标点对应一个数,现在需要对这些数排序从而达到对这些坐标点排序。有尝试过把点的坐标和它对应的值放在map中,然后对map中的元素用std::sort()进行排序,但是由于开始没有发现那个重载符号的使用,所以没有调试成功。现在直接不用map了,而是用vector,vector里面放的是带有坐标点和其对应值的struct。
本次实验是在vector中存入3个结构体对象,每个结构体中放入一个二维点和它对应的值,然后采用sort()对齐排序,排序结果如下:
实验代码及注释
main.cpp:
代码如下:
#include iostream
#include vector
#include map
#include algorithm
#include opencv2/core/core.hpp
#include opencv2/highgui/highgui.hpp
using namespace std;
using namespace cv;
typedef struct
{
cv::Point point;
long point_value;
} PAIR;
/*按照降序排列*/
bool operator(const PAIR &x, const PAIR &y)
{
return x.point_value y.point_value;
}
///*按照降序排列*/
//bool compare(const PAIR &x, const PAIR &y)
//{
// return x.point_value y.point_value;
//}
void main()
{
PAIR pair1, pair2, pair3;
std::vectorPAIR vec;
pair1.point = Point(10, 20);
pair1.point_value = 100;
pair2.point = Point(70, 30);
pair2.point_value = 99;
pair3.point = Point(44, 76);
pair3.point_value = 101;
vec.push_back(pair1);
vec.push_back(pair2);
vec.push_back(pair3);
// std::sort(vec.begin(), vec.end(), compare);
std::sort(vec.begin(), vec.end());
cout "排序的结果为:" endl;
for(vectorPAIR::iterator it = vec.begin(); it != vec.end(); ++it) {
cout it-point endl;
}
return ;
}
实验总结
std::sort()函数的功能很强大,且可以对类,结构体等元素进行排序。