你的浏览器版本过低,可能导致网站不能正常访问!
为了你能正常使用网站功能,请使用这些浏览器。

Python 中、C++ 中的排序

[复制链接]
gaosmile 发布时间:2020-9-17 15:30

Python 中的排序

在 Python 中,常用的排序就是 sorted ,对于列表这种数据结构来说,还有 sort 方法

列表的排序

使用 sort 方法进行排序,以第二个值进行升序排序,列表的 sort 方法是原地排序

另外一种排序方法是 sorted ,此方法不是原地排序,以第一个值进行排序,同样也是默认升序排序

字典排序

有时候我们也需要对字典进行排序,也是使用 sorted 函数,不过对字典排序后返回的是列表,列表中是元组(tuple)

C++ 中的排序

对 vector 排序

要对 vector 容器中的元素排序,可以使用 algorithm 算法库中的 sort 函数

#include #include #include using namespace std; int main() {  vector a;  cout << "sort before" << endl;  for (int i = 0; i <10; i++){   a.push_back(10-i);   cout << a << "  ";  }  cout << endl;  cout << "sort after" << endl;  sort(a.begin(), a.end());  //   for (int i = 0; i < 10; i++)  {   cout << a << "  " ;  }  cout << endl;  return 0; }

对 2 维vector  排序

类似于 Python ,我们也可以指定根据哪个元素进行排序

#include #include #include using namespace std; # 根据第二个元素进行排序 bool sort_by_second_val(vector v1, vector v2) {  return v1[1] > v2[1]; } int main() {     // 模拟一个输入  vector < vector> arr;  for (int i = 0; i < 10; i+=2)  {   vector temp;   temp.push_back(i);   temp.push_back(i+1);   arr.push_back(temp);  }     // 排序前:arr = [[0, 1], [2, 3], [4, 5], [6, 7],[8, 9]]  sort(arr.begin(), arr.end(), sort_by_second_val);     // 排序后:arr = [[8, 9], [6, 7], [4, 5], [2, 3],[0, 1]]  return 0; }

对结构体进行排序

模拟一个学生管理系统,依次创建学生信息,然后加入到 vector 中,接着对学生的年龄进行排序

#include #include #include #include  using namespace std; struct Studen{  string name;  int age; }; bool sort_by_age(Studen s1, Studen s2) {  return s1.age<  s2.age; } int main() {  vector studens;  // 用来存储所有学生的信息  Studen s1, s2, s3;   // 创建 3 个学生  s1.name = "xx";  s1.age = 20;  studens.push_back(s1);  s2.name = "yy";  s2.age = 18;  studens.push_back(s2);  s3.name = "zz";  s3.age = 10;  studens.push_back(s3);  sort(studens.begin(), studens.end(), sort_by_age);  return 0; }

排序前

排序后




收藏 评论0 发布时间:2020-9-17 15:30

举报

0个回答

所属标签

STM32团队

意法半导体微控制器和微处理器拥有广泛的产品线,包含低成本的8位单片机和基于ARM® Cortex®-M0、M0+、M3、M4、M33、M7及A7内核并具备丰富外设选择的32位微控制器及微处理器


最新内容

关于
我们是谁
投资者关系
意法半导体可持续发展举措
创新与技术
意法半导体官网
联系我们
联系ST分支机构
寻找销售人员和分销渠道
社区
媒体中心
活动与培训
隐私策略
隐私策略
Cookies管理
行使您的权利
官方最新发布
STM32N6 AI生态系统
STM32MCU,MPU高性能GUI
ST ACEPACK电源模块
意法半导体生物传感器
STM32Cube扩展软件包
关注我们
微信公众号二维码 微信公众号
手机版二维码 手机版