c++stl 排序算法使用集

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35119182/article/details/87900476

目录

c++对自定义数据类型进行排序

sort 高级用法

复杂数据类型实现比较最大最小 max/min

归并排序

监测数据是否包含  includes()

合并,但是不去重复set_union 函数

自动对字符串排序

快速排序 nth_element 函数

c++11 新增算法


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

c++对自定义数据类型进行排序

怎么排序呀,可以使用运算符重载+stl容器和sort排序对自定义的数据类型排序。

struct student {

    int course;
    int name;
    student(student &s){ ... } // 深拷贝
    bool operator < (const student &s2){  // < 运算符重载
        return this->score < s2.score;
    }
}

int main(){
    
    vector<student> s{{100,"songchao"},{99,"xiaochao"}};
    partial_sort(s.begin(),s.begin()+1,s,end());  // 这里为什么不用sort呢,因为short只能是对数组进行排序,例如list,set底层分别是链表和红黑树
    for(auto i:s){
        cont << i >>endl;
    }    
}

sort 高级用法

int a[3]={2,1,9};
sort(a,a+3,[](int a.int b){ return a<b;});  // <  > 的修改编程 从小到大,从大到小

//  1 2 9  

//取最大值
*min_element(a,a+3);  // 1
//取最小值
*max_element(a,a+3);  // 9

复杂数据类型实现比较最大最小 max/min

int num1 = max(100,90);
cout << max((char*)"123",(char*)"234",[](const char *str1,const char* str2)->bool { return strcmp(str1,str2)<0:1?0; });

输入:234

非基本数据类型都需要运算符重载排序

归并排序

首先依赖有序

int a[4]={2,4,1,9};
int b[2]={1.22};
sort(a,a+4,[](int a,int b){ return a>b;});
sort(b,b+2,[](int a,int b){ return a>b;});
//归并排序  --前提是要有序
merge(a,a+4,b,b+2,c,[](int a,int b){ return a>b;});  // 拼接
for(auto i:c){
    cout << c <<endl;
}

监测数据是否包含  includes()

int a[4]={2,4,1,9};
int b[2]={1.9};
bool check = includes(a,a+4,b,b+2);
if(check){
    cout << "包含";
}else cout << "不包含";

// 输出:包含

合并,但是不去重复set_union 函数

int a[4]={2,4,1,9};
int b[2]={1.9};
int c[15]{0};
set_union(a,a+4,b,b+2,c);
for(auto i:c){
    cout<<i<<endl;
}

prev_permutation 随机打乱 对调元素排序,两两交换--类似冒泡排序。 做排列,有序不做排列

可以用来套别人密码,可出现n种方式。

next_permutation  组合

自动对字符串排序

char *s1 = "xxoo";
char *s2 = "hello";
bool res = lexicographical_comare(s1,s1+strlen(s1),s2,s2+strlen(s2)); //自动对字符串排序
if(res){
    cout << "s1在s2前面"<<endl;
}else 
    cout << "s1在s2后面"<<endl;

// 输出: s1在s2后面

快速排序 nth_element 函数

随便数组中找一个数据,将大于它的放右边,小于它的放左边。

int a[4]={2,5,99,1};
nth_element(a,a+1,a+4);   // 以a+1 对应数组5为中心,小于向左,大于向右
for_each(a,a+4,[](int x){ cout << x <<endl; });

c++11 新增算法

int a = min({1,2,3}); // 1

int b = max({1,2,3});// 3  专门处理了大括号


auto it = minmax({1,2,3});

cout<<it.first<<endl; 最大

cout<<it.second<<endl; 最小

all_of // 全部满足
any_of // 至少满足一个
none_of // 一个都不满足

vector<int> s{1,3,4};
bool res = all_of(s.begin(),s.end(),[](int i)->bool { return i%2==0; });  // 条件自己定义:判断有没有偶数
if(res){
    cout<<"全部满足"<<endl;
}else 
    cout<<"不满足"<<endl;

压缩容器

find_if

find_if_ont

copy_if

例子:1 2 3 4 5 个数我现在只要奇数,1 3 5那么久只需要 三个存储空间就可以了那么怎么实现呢

vector<int> v1{1,2,3,4,5};
vector<int> v2(v1.size());
auto it=copy_if(v1.begin(),v1.end(),v2.begin(),[](int i){ return i %2; } );
v1.resize(distance(v2.begin(),it));  // 压缩容器

猜你喜欢

转载自blog.csdn.net/qq_35119182/article/details/87900476