学习C++:STL算法

STL算法就是像查找、搜索、删除等操作的通用函数,其应用范围很广。要使用STL算法,应用程序必须包含头文件:

#include <algorithm>

使用STL算法

1.count()与count_if()
算法std:::count()和count_if()计算给定范围内的元素数。
下面演示使用STL算法std::count()和count_if()分别计算有多少个元素包含指定值和满足指定条件:

#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
template<typename elementType>
bool IsEven(const elementType& number)//一元谓词
{
	return {(number%2)==0};
}
int main()
{
	vector<int>vecIntegers;
	for(int nNum=1;nNum<20;++nNum)
		vecIntegers.push_back(nNum);//产生一个1到19的数组
	size_t nNumZeroes=count(vecIntegers.begin(),vecIntegers.end(),0);
	cout<<"数组中存在0的个数为:"<<nNumZeroes<<endl;
	size_t nNumEvenElements=count_if(vecIntegers.begin(),vecIntegers.end(),IsEven<int>);
	cout<<"数组中存在偶数的个数为:"<<nNumEvenElements<<endl;
	return 0;
}

2.search与search_n()
search()用于在一个序列中查找另一个序列
search_n()用于在容器中查找n个相邻的指定值
两个函数都返回一个迭代器,它指向找到的第一个模式。使用迭代器之前,务必将其与end()进行比较。
下面将演示如何使用search()和search_n()在集合中查找序列。

auto iRange1=search(vecIntegers.begin()   //集合首
				  ,vecIntegers.end()     //集合尾
				  ,listIntegers.begin()  //查找序列首
				  ,listIntegers.end());  //查找序列尾

auto iRange2=search_n(vecIntegers.begin()  //搜索{9,9,9}在vecIntegers中首次出现的位置
					,vecIntegers.end()
					,3   //相同待查找元素的个数
					,9); //待查找的元素
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI 菌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值