STL之sort应用

简介: STL之sort应用

前言


顾名思义,sort()是标准库中的排序算法,能用此算法的容器是支持随机访问的容器:vector, deque, string,array。

其有两种形式,第一种sort(a,b),其中a,b为排序的地址范围,为[a,b),此时用operator<作比较,默认升序排序。

第二种sort(a,b,comp),此时采用comp进行比较,comp带两个同类型的参数,如果第一个参数排在第二个参数前面,返回true,否则返回false,它可以是函数指针,也可以是函数对象,即仿函数。

下为几个常见的仿函数:

less(小于)

greater(大于)

equal_to(等于)

not_equal_to(不相等)

less_equal(小于等于)

greater_equal(大于等于)

须注意不能直接写入仿函数的名字,而是要写其重载的()函数:

less<>()

greater<>()


常见sort分类


1.全排序


sort 和 stable_sort,前者不稳定,采用快排,后者为稳定排序,归并排序


2.部分排序


partial_sort,如part_sort(a,a+n,comp);只排前n个,采用堆排序,显然适用于求解topn问题。


结构体排序


针对两种sort的两种形式主要有两种应用形式。


1.运算符重载


采用sort(a,b),或者只想利用上述常见的伪函数,需要用到运算符重载。

#include<iostream>
#include<algorithm> 
#include<string>
using namespace std;
struct student{
  string name;
  int age;
  bool operator<(const student &a)const{//运算符重载 
  if(name==a.name)return age<a.age;
  return name<a.name; 
  }
};
int main(){
  student s[3] ;
  s[0].name="Kndy";s[0].age=12;
  s[1].name="Anm";s[1].age=17;
  s[2].name="Kndy";s[2].age=11;
  sort(s,s+3);
  for(int i=0;i<3;i++)
  cout<<s[i].name<<"  "<<s[i].age<<endl;
  return 0;
}


输出结果:

1685008737177.jpg

若上述重载是对>重载,排序改为:sort(s,s+3,greater<student>());,降序排序,结果为:

1685008744490.jpg


2.比较函数


此时需自己定义一个比较函数,如果第一个参数排在第二个参数前面,返回true,否则返回false。

#include<iostream>
#include<algorithm> 
#include<string>
using namespace std;
struct student{
  string name;
  int age;
};
bool comp(const student &a,const student &b){
  if(a.name==b.name)return a.age<b.age;
  return a.name<b.name;
}
int main(){
  student s[3] ;
  s[0].name="Kndy";s[0].age=12;
  s[1].name="Anm";s[1].age=17;
  s[2].name="Kndy";s[2].age=11;
  sort(s,s+3,comp);
  for(int i=0;i<3;i++)
  cout<<s[i].name<<"  "<<s[i].age<<endl;
  return 0;
}


显然此时应该是升序排序结果如下:

1685008577635.jpg

相关文章
|
7天前
|
存储 安全 算法
C++的内置数组和STL array、STL vector
C++的内置数组和STL array、STL vector
|
2月前
|
C++ 容器
|
2月前
|
存储 算法 Linux
【STL】:vector用法详解
【STL】:vector用法详解
57 1
|
11月前
|
存储 C语言 C++
C++ STL list
上次我们详细的介绍了vector,今天我们继续来介绍一下TSTL中的另外一个容器list。list在基础的功能和结构上就是一个双向带头的循环链表,实现起来基本不难,但是list迭代器的封装是非常值得学习的。
|
存储 搜索推荐 C++
C++【STL】之list的使用
C++ STL list类常用接口详细讲解,干货满满!
66 0
C++【STL】之list的使用
|
算法 C++ 容器
【C++】STL——list的使用
【C++】STL——list的使用
【C++】STL——list的使用
|
人工智能 算法 C++
c++ stl vector 的相关用法
c++ stl vector 的相关用法
74 0
c++ stl vector 的相关用法
c++STL vector的用法详解
c++STL vector的用法详解
98 0