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); //待查找的元素