C++泛型算法
搜索(search)算法:find()、find_if()、search()、binary_search()【二分查找】、count【计数】()和count_if()
分类排序(sorting)与通用排序(ordering)算法:sort()、partial_sort()【局部】、merge()【合并】、partition()【分】、rotate()【轮流】、reverse()【反转】和randow_shuffle()【随机洗牌】
删除(deletion)算法:unique()【唯一】和remove(清除)
算术(numeric)算法:accumulate()【积累+】、partial_sum()【部分求和】、inner_product()【内生产】、和adjacent_difference()【临近差异】
生成(generation)和变异(mutation)算法:generate()【产生】、fill()、transformation()【转型】、copy()和for_each()
关系(relation)算法:equal()【等于】、min()和max()
泛型算法接受一对迭代器,他们标记了要遍历元素的范围。
例子:
#include <vector>#include <algorithm>
#include <iostream>
using namespace std;
int ia[10]={119,39,41,83,90,47,38,76,81,26};
int main(){
vector<int> vec(ia,ia+10);
//未排序前数组输出
int i;
vector<int>::iterator iter;
cout<<"未排序前的数组:"<<endl;
for(iter=vec.begin();iter<vec.end();iter++){
cout<<*iter<<" ";
}
cout<<endl;
//只排序前4个元素
sort(vec.begin(),vec.begin()+4);
cout<<"只排序前4个元素:"<<endl;
iter=vec.begin();
do{
cout<<*iter<<" ";
iter++;
}while(iter!=vec.end());
cout<<"\r\n";
//排序数组
sort(vec.begin(),vec.end());
cout<<"排序后的数组:"<<endl;
iter=vec.begin();
while(iter!=vec.end()){
cout<<*iter<<" ";
iter++;
}
cout<<endl<<"反转数组:"<<"\r\n";
//反转数组
reverse(vec.begin(),vec.end());
for(iter=vec.begin();iter!=vec.end();){
cout<<*iter<<" ";
iter++;
}
cout<<endl<<"搜索数组某值:"<<endl;
//
int search_value;
cout<<"请输入你要搜索的值:";
cin>>search_value;
vector<int>::iterator found;
found=find(vec.begin(),vec.end(),search_value);
if(found!=vec.end()){
cout<<"你要搜索的值: "<<search_value<<" 在数组中的索引是: "<<found-vec.begin()<<endl;
}else{
cout<<"你要搜索的值: "<<search_value<<" 没有找到!"<<endl;
}
}