非变异算法 主要函数

(1) 计数   

count(): 在序列中统计某个值出现的次数。

原型:

  template<class InIt,class T>

size_t count(InIt first,InIt last ,const T& val);

参数说明:InIt 输入迭代器,first 表示起始元素的迭代器指针,last表示结束元素的迭代器指针。

T: 模板参数类型

该函数返回[first,last)间的元素数目,这些元素满足 *(first+i)=val;

count_if() :在序列中统计与某谓词(表达式)匹配的次数。

 

示例一:求数组中有多少个0

#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int a[]={0,1,2,0,8,0,3};
const int N=sizeof(a)/sizeof(int);
cout<<"Number of zeros:"<<count(a,a+N,0)<<endl;
return 0;
}

 

 

示例二:查询有多少个学生成绩为80分

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
class Student
{
int NO;
string name;
int grade;
public:
Student(int NO,string name,int grade)
{
this->NO=NO;
this->name=name;
this->grade=grade;
}
bool operator==(int grade)
{
return this->grade==grade; //相等则为true,否则为false

//if(this->grade>grade) return true;     //如果改成这两行,那么结果就是求grade以上的学生的人数
//else return false;


}
};
int main()
{
vector<Student>v;
Student s1(1000,"zhangsan",80);
Student s2(1001,"lisi",85);
Student s3(1002,"wangwu",80);
Student s4(1003,"zhaoliu",80);
v.push_back(s1);
v.push_back(s2);
v.push_back(s3);
v.push_back(s4);
int ncount=count(v.begin(),v.end(),80);
cout<<"成绩为80分的人数为:"<<ncount<<endl;
}

此函数主要理解必须重载Student类的运算符"==",这是因为当执行int ncount=count(v.begin(),v.end(0,80)时,要比较[v.begin,v.end)中各Student对象是否与80相等。

 

(2) 比较

equal() 两个序列中的对应元素都相同时为真。

原型:

template<class InIt1,class InIt2>

bool equal(InIt1 first,InIt1 last,InIt2 x);

template<class InIt1,class InIt2,class Pred>

bool equal(InIt1 first,InIt1 last,InIt2 x,Pred pr);

参数说明: Init1 :第一个容器的迭代器,first表示起始元素的迭代器指针,last表示结束元素的迭代器指针。

               Init2 :第二个容器的迭代器。

               Pred:二元全局函数或函数对象。

mismatch() :找出两个序列相异的第一个元素。

 

(3) 查询

find() :在单迭代器序列中找出某个值第一次出现的位置。

原型:

template<class InIt,class T>

InIt find(InIt first,InIt last,const T& val);

说明: InIt输入迭代器,first表示起始元素的迭代器指针,last表示结束元素的迭代器指针。

          T :模板类型参数

该函数是查询[first,last)间迭代器对应的元素值是否有等于val的,若有则返回其迭代器指针;若无则返回last。    

         易知,查询元素的个数范围(N)是[0,last-first),由于要判定*(first+N)==val,因此模板T对应的类必须重载运算符“operator==”。

 

posted @ 2014-04-01 18:25  zhoudan  阅读(114)  评论(0编辑  收藏  举报