STL---基本算法---<stl_algobase.h>概述
通过一个实例来说明这些算法的接口使用:
#include <iostream> #include <algorithm> #include <functional> #include <vector> #include <cstring> using namespace std; template <class T> struct display{ void operator()(const T& x)const{ cout<<x<<" "; } }; int main() { int ia[9]={0,1,2,3,4,5,6,7,8}; vector<int> iv1(ia,ia+5); vector<int> iv2(ia,ia+9); cout<<equal(iv1.begin(),iv1.end(),iv2.begin())<<endl;//1,true fill(iv1.begin(),iv1.end(),9);//区间全部填9 for_each(iv1.begin(),iv1.end(),display<int>()); cout<<endl; fill_n(iv1.begin(),3,7); for_each(iv1.begin(),iv1.end(),display<int>()); cout<<endl; string s1[]={"jamie","jjHou","jason"}; string s2[]={"jamie","jjhou","jerry"}; cout<<lexicographical_compare(s1,s1+2,s2,s2+2)<<endl; cout<<lexicographical_compare(s1,s1+2,s2,s2+2,greater<string>())<<endl; //字典序对比,s1小于s2 return 0; }
在看下面一些算法:
#include <iostream> #include <algorithm> #include <functional> #include <vector> #include <cstring> #include <set> #include <iterator> using namespace std; template <class T> //这是一个函数对象 struct display{ void operator()(const T& x)const{ cout<<x<<" "; } }; int main() { int ia[]={0,1,2,3,4,5,6,6,6,7,8}; vector<int> iv(ia,ia+sizeof(ia)/sizeof(int)); cout<<count(iv.begin(),iv.end(),6)<<endl;//找出元素值为6的个数 cout<<count_if(iv.begin(),iv.end(),bind2nd(less<int>(),7))<<endl; cout<<*find_if(iv.begin(),iv.end(),bind2nd(greater<int>(),2))<<endl; for_each(iv.begin(),iv.end(),display<int>()); cout<<endl; reverse(iv.begin(),iv.end()); //逆序重排 for_each(iv.begin(),iv.end(),display<int>());//输出每一个元素 cout<<endl; int ia2[]={0,1,2}; vector<int> iv2(ia2,ia2+3); vector<int>::iterator ite=find_first_of(iv.begin(),iv.end(),iv2.begin(),iv2.end()); //在第一个区间序列中查找第二序列中任意元素第一次出现的位置,返回该位置的迭代器 while(ite!=iv.end()) { cout<<*ite<<" "; ite++; } return 0; }