c++algorithm库部分函数(1)

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool isOdd(int i)
{
	return (i % 2 == 1);
}
void func(int i)
{
	cout << i << endl;
}
int main()
{
	vector<int> data;
	data.push_back(10);
	data.push_back(21);
	data.push_back(30);
	//find函数如果找到所需的值则返回该值指针,否则返回end指针
	cout << "find()-----------------" << endl;
	auto a = find(data.begin(), data.end(), 50);
	cout << *(--a) << endl;
	//find_if函数根据自定义函数找到符合的第一个值并返回;find_if_not即返回不满足条件的第一个值
	cout << "find_if()-----------------" << endl;
	auto b = find_if(data.begin(),data.end(),isOdd);
	cout << *b << endl;
	//for_each函数将容器的值作为回调函数的实参
	cout << "for_each()-----------------" << endl;
	for_each(data.begin(), data.end(), func);
	//search函数求某一个容器是否包含另一个容器,值的顺序需要相同
	vector<int> a1;
	a1.push_back(10);
	a1.push_back(20);
	a1.push_back(30);
	int a2[] = {20,30};
	auto it1=search(a1.begin(),a1.end(),a2,a2+2);
	cout << "search()-----------------" << endl;
	if (it1 != a1.end())
	{
		cout << it1 - a1.begin() << endl;
	}
	//search_n函数用于寻找在某一容器中是否存在固定数量的值,且需要连续
	int b1[] = {10,20,20,30,40};
	vector<int> b2(b1,b1+5);
	auto it = search_n(b2.begin(),b2.end(),2,20);
	cout << "search_n()-----------------" << endl;
	cout << it - b2.begin() << endl;
	//sort函数排序,默认从小到大
	cout << "sort()-----------------" << endl;
	int b3[] = {1,3,4,2,0};
	sort(b3, b3 + 5);
	for_each(b3,b3+5,func);
}

输出结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值