C++学习之库函数<algorithgm>(1)

来源:互联网 发布:双十一淘宝客服回复 编辑:程序博客网 时间:2024/05/22 09:39
<algorithm>算法库



adjacent_find查找两个相邻(Adjacent)的等价(Identical)元素函数:adjacent_find(first,last,Binary)

解释:first:指向序列的初始地址。
           last:指向序列的末地址,但不包括last指向的元素。
           Binary:二元谓词函数,以两个元素为参数,然后返回一个可转换成bool类型的值。

返回:指向在范围[first,last)中第一对匹配的相邻元素的第一个元素的地址。如果不存在相邻满足条件的,则返回last

实例1:
#include<iostream>#include<algorithm>using namespace std;int comp(int a,int b)//自定义二元谓词函数{return a>b;//满足前者元素大于后者元素}int main(){int c[]={5,2,3,4,4,5,6};int *p=adjacent_find(c,c+7,comp);//c为数组首地址,c+7为末地址cout<<*p<<' '<<*(p+1)<<endl;return 0;}/*运行结果:5 2*/
实例2:
#include<iostream>#include<algorithm>using namespace std;int comp(int a,int b)//自定义二元谓词函数{return a==b;//满足前者元素大于后者元素}int main(){int c[]={5,2,3,4,4,5,6};int *p=adjacent_find(c,c+7,comp);//c为数组首地址,c+7为末地址cout<<*p<<' '<<*(p+1)<<endl;return 0;}/*运行结果:4 4*/



count返回值等价于给定值的元素的个数函数:count(first,last,val)

解释:first:指向序列的初始地址。
           last:指向序列的末地址,但不包括last指向的元素。
           val:需要匹配的值。

返回:指向在范围[first,last)中与val等值的元素个数。

实例1:
#include<iostream>#include<algorithm>using namespace std;int main(){int c[]={5,2,3,4,4,5,6};cout<<count(c,c+7,4)<<endl;return 0;}/*运行结果:2*/
实例2:
#include<iostream>#include<algorithm>using namespace std;int main(){int c[]={5,2,3,4,4,5,6};cout<<count(c,c+7,1)<<endl;return 0;}/*运行结果:0*/



count_if返回值满足给定条件的元素的个数
函数:count_if(first,last,pred)

解释:first:指向序列的初始地址。
           last:指向序列的末地址,但不包括last指向的元素。
           pred:一元谓词函数。以范围内一个元素为参数,然后返回一个可转换成bool类型的值。

返回:返回范围[first,last)中使谓词函数返回true的元素个数。

实例1:
#include<iostream>#include<algorithm>using namespace std;int pred(int a){return a>=4;}int main(){int c[]={5,2,3,4,4,5,6};cout<<count_if(c,c+7,pred)<<endl;return 0;}/*运行结果:5*/
实例2:
#include<iostream>#include<algorithm>using namespace std;int pred(int a){return a>9;}int main(){int c[]={5,2,3,4,4,5,6};cout<<count_if(c,c+7,pred)<<endl;return 0;}/*运行结果:0*/



equal返回两个范围是否相等
函数:equal(first,last,Binary)

解释:first1:指向序列1的初始地址。
           last1:指向序列1的末地址,但不包括last指向的元素。
           first2:指向序列2的初始地址。
           Binary:二元谓词函数,以两个元素为参数,然后返回一个可转换成bool类型的值。

返回:如果范围[first1,last1)中的所有元素与从first2开始的范围中所有元素等价,则返回ture,否则返回false

实例1:
#include<iostream>#include<algorithm>using namespace std;int main(){int a[]={2,5,6,3,1};int b[]={2,5,6,3,1};puts(equal(a,a+5,b)?"yes":"no");return 0;}/*运行结果:yes*/
实例2:
#include<iostream>#include<algorithm>using namespace std;int main(){int a[]={2,2,6,3,1};int b[]={2,5,6,3,1};puts(equal(a,a+5,b)?"yes":"no");return 0;}/*运行结果:no*/


原创粉丝点击