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

<algorithm>算法库



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

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

返回:指向在范围[first,last)中与val等值的第一个元素的地址。如果不存在,则返回last

实例1:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int a[]={2,2,6,3,1};
	cout<<find(a,a+5,6)-a+1<<endl;
	return 0;
}
/*
运行结果:
3
*/
实例2:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int a[]={2,2,6,3,1};
	cout<<find(a,a+5,5)-a+1<<endl;//查找5,不存在返回出界
	return 0;
}
/*
运行结果:
6
*/



find_if 查找范围 A 中与范围 B 等价的子范围最后出现的位置
函数:find_if(first,last,pred)

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

返回:指向在范围[first,last)中使谓词函数反悔true的第一个元素的地址。如果不存在,则返回last

实例1:
#include<iostream>
#include<algorithm>
using namespace std;
int pred(int a)
{
	return a>5;
}
int main()
{
	int a[]={2,2,6,3,1};
	cout<<*find_if(a,a+5,pred)<<endl;
	return 0;
}
/*
运行结果:
6
*/
实例2:
#include<iostream>
#include<algorithm>
using namespace std;
int pred(int a)
{
	return a<2;
}
int main()
{
	int a[]={2,2,6,3,1};
	cout<<find_if(a,a+5,pred)-a+1<<endl;//返回小于2的第一个元素的位置
	return 0;
}
/*
运行结果:
5
*/




search 在范围 A 中查找第一个与范围 B 等价的子范围的位置
函数:search(first1,last1,first2,Binary)

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

返回:返回指向序列[first2,last2)在序列[first1,last1)第一次出现位置处的第一个元素的地址。

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



copy 将一个范围中的元素拷贝到新的位置处
函数:copy(first1,last1,first2)

解释:first1:指向序列1的初始地址。
           last1:指向序列1的末地址,但不包括last指向的元素。
           first2:指向序列2的初始地址。

实例1:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int a[]={2,2,6,3,1};
	int b[10];
	copy(a,a+5,b);
	for(int i=0;i<5;i++)
		cout<<b[i]<<' ';
	return 0;
}
/*
运行结果:
2 2 6 3 1
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值