
#include<algorithm>中常用函数的使用
发布日期:2021-05-08 05:04:39
浏览次数:21
分类:原创文章
本文共 2279 字,大约阅读时间需要 7 分钟。
#include< algorithm >是C++的标准模版库(STL)中最重要的头文件之一,提供了大量基于迭代器的非成员模板函数。以下将介绍几个常用的库函数:
一、max(),min()和swap()
- max(x,y) //返回两个元素中值最大的元素
- min(x,y) //返回两个元素中值最小的元素
- swap(x,y) //用来交换x和y的值
二、reverse()
反转排序指定范围中的元素,reverse(a,b) 可以将数组指针在[a,b)之间的元素或容器的迭代器在[a,ib)范围内的元素进行反转。
程序示例:
#include<iostream>#include<algorithm>#include<string>using namespace std; int main(){ int a[10]={ 1,2,3,4,5,6,7,8,9,10}; reverse(a,a+6); for(int i=0;i<10;i++){ cout<<a[i]<<" "; } cout<<endl; string str="abcdefgh"; reverse(str.begin()+2,str.begin()+6); for(int j=0;j<str.length();j++){ cout<<str[j]<<" "; } cout<<endl; return 0;}
运行结果:
三、fill()
fill() 可以把数组或容器中的某一段区间赋为某个相同的值。
程序示例:
#include<iostream>#include<algorithm>using namespace std; int main(){ int a[5]; fill(a,a+5,957); for(int i=0;i<5;i++) { cout<<a[i]<<" "; } cout<<endl; return 0;}
运行结果:
四 、 sort()
排序函数,默认为递增排序。
如果需要递减排序,需要增加一个比较函数:
bool cmp(int a,int b){ return a>b; //若a<b为递增排序}sort(a,a+n,cmp);
程序示例:
#include<iostream>#include<algorithm>using namespace std;bool cmp(int a,int b){ return a>b;}int main(){ int i; int a[7]={ 8,6,9,2,7,4,3}; cout<<"排序前数组为:"; for(i=0;i<7;i++) { cout<<a[i]<<" "; } cout<<endl; sort(a,a+7); cout<<"递增排后前数组为:"; for(i=0;i<7;i++) { cout<<a[i]<<" "; } cout<<endl; sort(a,a+7,cmp); cout<<"递减排后前数组为:"; for(i=0;i<7;i++) { cout<<a[i]<<" "; } cout<<endl; return 0;}
运行结果:
五、next_permutation()
返回给定范围中的元素组成的下一个按字典序的排列,即给出一个序列在全排列中的下一个序列。
程序示例:
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[5]={ 1,2,3}; do{ cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl; }while(next_permutation(a,a+3)); return 0;}
运行结果:
六、lower_bound()和upper_bound()
lower_bound 和 upper_bound()需要用在一个有序数组或容器中。
lower_bound(first,last,val) 用来寻找在数组或容器的[first,last)范围内第一个值大于等于val元素的位置,如果是数组,返回该位置的指针;若果是容器,返回该位置的迭代器
upper_bound(first,last,val) 用来寻找在数组或容器的[first,last)范围内第一个值大于val元素的位置,如果是数组,返回该位置的指针;若果是容器,返回该位置的迭代器
程序示例:
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[10]={ 1,2,2,3,3,4,4,5,6,7}; int *lowerPos=lower_bound(a,a+10,3); int *upperPos=upper_bound(a,a+10,3); cout<<"lower_bound(a,a+10,3)="<<lowerPos-a<<endl; cout<<"upper_bound(a,a+10,3)="<<upperPos-a<<endl; return 0; }
运行结果:
发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2025年03月23日 13时32分54秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
数据仓库建模方法论
2021-05-09
数据仓库之拉链表
2021-05-09
虚拟机搭建hadoop环境
2021-05-09
DataStax Bulk Loader教程(四)
2021-05-09
物联网、5G世界与大数据管理
2021-05-09
Cassandra与Kubernetes
2021-05-09
.NET应用框架架构设计实践 - 概述
2021-05-09
Rust 内置 trait :PartialEq 和 Eq
2021-05-09
Hibernate(十四)抓取策略
2021-05-09
Mybatis入门之增删改查
2021-05-09
[菜鸟的设计模式之旅]观察者模式
2021-05-09
Spring-继承JdbcDaoSupport类后简化配置文件内容
2021-05-09
Java基础IO流(一)
2021-05-09
Hibernate入门(四)---------一级缓存
2021-05-09
MySQL事务(学习笔记)
2021-05-09
一个web前端开发者的日常唠叨
2021-05-09
内存分配-slab分配器
2021-05-09
技术写作技巧分享:我是如何从写作小白成长为多平台优秀作者的?
2021-05-09
Jupyter Notebook 暗色自定义主题
2021-05-09
[Python学习笔记]组织文件
2021-05-09