1.for_each 用法:for_each(容器起始地址芥永,容器結(jié)束地址叔扼,要執(zhí)行的方法)
include <iostream>
include <algorithm>
include <vector>
using namespace std;
template<class T>
struct plus2
{
void operator()(T&x)const
{
x+=2;
}
};
void printElem(int& elem)
{
cout << elem << endl;
}
int main()
{
int ia[]={0,1,2,3,4,5,6};
for_each(ia,ia+7,printElem);//輸出
int ib[]={7,8,9,10,11,12,13};
vector<int> iv(ib,ib+7);
for_each(iv.begin(),iv.end(),plus2<int>());//更改元素
for_each(iv.begin(),iv.end(),printElem);//輸出
return 0;
}
2.find算法
用法:
int *find(int *begin哀蘑,int *end顿苇,int value)
在前閉后合的區(qū)間 begin撩满,end中蜒程,查找value如果查找到了就返回第一個符合條件的元素,否則返回end指針
include <iostream>
include <algorithm>
using namespace std;
void printElem(int& elem)
{
cout << elem << endl;
}
int main()
{
int ia[]={0,1,2,3,4,5,6};
int *i= find(ia,ia+7,9);//在整個數(shù)組中查找元素 9
int *j= find(ia,ia+7,3);//在整個數(shù)組中查找元素 3
int end=ia+7;//數(shù)組最后位置
if(i == end)
cout<<"沒有找到元素 9"<<endl;
else
cout<<"找到元素9"<<endl;
if(j == end)
cout<<"沒有找到元素 3"<<endl;
else
cout<<"找到元素"<<j<<endl;
return 0;
}
- copy算法
include <iostream>
include <algorithm>
include <deque>
using namespace std;
template<class T>
struct display
{
void operator()(const T &x)const
{
cout<<x<<" ";
}
};
int main()
{
int ia1[]={0,1,2,3,4,5,6,7,8};
copy(ia1+2,ia1+7,ia1);//將下標(biāo)2-6復(fù)制給 1-5
for_each(ia1,ia1+9,display<int>()); //2,3,4,5,6,5,6,7,8
cout<<endl;
int ia2[]={0,1,2,3,4,5,6,7,8};
copy(ia2+2,ia2+7,ia2+4);//將下標(biāo)2-6復(fù)制給 4-8
for_each(ia2,ia2+9,display<int>()); //0,1,2,3,2,3,4,5,6
cout<<endl;
int ia3[]={0,1,2,3,4,5,6,7,8};
deque<int> id(ia3,ia3+9);
deque<int>::iterator first=id.begin();
deque<int>::iterator last=id.end();
deque<int>::iterator result=id.begin();
++++first;
cout<<*first<<endl;
----last;
cout<<*last<<endl;
cout<<*result<<endl;
copy(first,last,result);
for_each(id.begin(),id.end(),display<int>());//2,3,4,5,6,5,6,7,8
cout<<endl;
int ia4[]={0,1,2,3,4,5,6,7,8};
deque<int> ide(ia4,ia4+9);
deque<int>::iterator first1=ide.begin();
deque<int>::iterator last1=ide.end();
deque<int>::iterator result1=ide.begin();
advance(result1,4);//注意這里跟上面不一樣
++++first1;
cout<<*first1<<endl;
----last1;
cout<<*last1<<endl;
cout<<*result1<<endl;
copy(first1,last1,result1);
for_each(ide.begin(),ide.end(),display<int>());// 0,1,2,3,2,3,2,3,2不是預(yù)期的 0,1,2,3,2,3,4,5,6
cout<<endl;
return 0;
}