源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C++ 关于STL中sort()对struct排序的方法

  • 时间:2022-02-19 10:41 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C++ 关于STL中sort()对struct排序的方法
  [b]前言[/b]   一直没有系统去看过c++,因为懂得一些c的基本语法,在实际编程中用到c++,只能用到哪些看哪些,发现这样虽然能够完成大部分工作,但是有时候效率实在太低,比如说这节要讲的Std::sort()函数的使用,调了半天才调通。开通c/c++序列博客是记录在使用c++中一些难题,避免以后重犯错,当然以后会尽量挤出时间来较系统学习下c++。   开发环境:QtCreator2.5.1+OpenCV2.4.3   [b]实验基础[/b]   首先来看看std中的快速排序算法sort的使用方法:   [i][b]template <class RandomAccessIterator, class Compare> void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );[/b][/i]   这是一个带模板的函数,参数1和2表示需要排序的元素在随机迭代器的起始位置和结束位置,其迭代器指向的数据类型可以自己定义,常见的数据类型包括结构体,vector,类等都可以被使用。参数comp是用来决定所采用的排序是升序还是逆序的,默认情况下是升序排列。但是这种默认情况的优势是处理迭代器指向的元素为普通的数据类型,比如说整型,字符型等。如果指向的数据类型为类或者结构体,然后使用该类或者结构体中的某个元素进行排序,这时候需要自己定义排序的重载符号”<”。比如说在本次实验中该重载符号的定义为:
[u]复制代码[/u] 代码如下:
/*按照降序排列*/ bool compare(const PAIR &x, const PAIR &y) {     return x.point_value > y.point_value; }
  如果将comp定义为一个函数(网上好像很多都是用这种类似的函数),比如说该函数如下:
[u]复制代码[/u] 代码如下:
/*按照降序排列*/ bool operator<(const PAIR &x, const PAIR &y) {     return x.point_value > y.point_value; }
  则会报错如下错误:
  [img]http://files.jb51.net/file_images/article/201304/2013042511565348.png[/img]   std::sort因为函数参数不明确,所以无法推导出模板参数等.     [b]实验结果[/b]   本次实验是基于这样一个问题的:有一些坐标点集合(2d的坐标点,坐标点之间没有重复),每个坐标点对应一个数,现在需要对这些数排序从而达到对这些坐标点排序。有尝试过把点的坐标和它对应的值放在map中,然后对map中的元素用std::sort()进行排序,但是由于开始没有发现那个重载符号的使用,所以没有调试成功。现在直接不用map了,而是用vector,vector里面放的是带有坐标点和其对应值的struct。   本次实验是在vector中存入3个结构体对象,每个结构体中放入一个二维点和它对应的值,然后采用sort()对齐排序,排序结果如下:   [img]http://files.jb51.net/file_images/article/201304/2013042511565349.png[/img]   [b]实验代码及注释[/b]   [b]main.cpp: [/b]
[u]复制代码[/u] 代码如下:
#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::vector<PAIR> 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(vector<PAIR>::iterator it = vec.begin(); it != vec.end(); ++it) {         cout << it->point << endl;     }     return ; }
  [b]实验总结[/b]   std::sort()函数的功能很强大,且可以对类,结构体等元素进行排序。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部