for_each

for_each第一个参数和第二个参数是指定范围的,如果是容器,那么就那么写,如果是数组,就写指针,第三个参数的调用函数的名字,就是说对于第一个参数和第二个参数指定范围之中的每一个元素都会带入到第三个参数指定的函数中去。
 
#include<iostream> 
#include<vector> 
#include<algorithm> 
using namespace std; 


void show(int number) //将排序后的数字输出 
{ 
cout<<number<<endl; 

} 


int main() 
{ 
vector<int> getnumber; 
int x; 
int i=0; 
do{ 
cout<<"please enter a number,when you enter 0,this will end"<<endl; 
cin>>x; 
getnumber.push_back(x); 
}while(x!=0); 
int j=getnumber.size(); 
int t; 
for(i=0;i<j;i++) 
{ 
for(int m=j-1;m>i;m--) 
{ 
if(getnumber[m-1]>getnumber[m]) 
{ 
t=getnumber[m-1]; 
getnumber[m-1]=getnumber[m]; 
getnumber[m]=t; 
} 

} 
} 
cout<<"the result:"<<endl; 
for_each(getnumber.begin(),getnumber.end(),show); 
return 0; 
}
  
  
template <class InputIterator, class Function>
   Function for_each (InputIterator first, InputIterator last, Function f);
Apply function to range
Applies function f to each of the elements in the range [first,last).

The behavior of this template function is equivalent to:
1
2
3
4
5
6
template<class InputIterator, class Function>
  Function for_each(InputIterator first, InputIterator last, Function f)
  {
    for ( ; first!=last; ++first ) f(*first);
    return f;
  }



Parameters

first, last
Input iterators to the initial and final positions in a sequence. The range used is  [first,last), which contains all the elements between  first and  last, including the element pointed by  first but not the element pointed by last.
f
Unary function taking an element in the range as argument. This can either be a pointer to a function or an object whose class overloads  operator().
Its return value, if any, is ignored.

Return value

The same as f.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// for_each example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

void myfunction (int i) {
  cout << " " << i;
}

struct myclass {
  void operator() (int i) {cout << " " << i;}
} myobject;

int main () {
  vector<int> myvector;
  myvector.push_back(10);
  myvector.push_back(20);
  myvector.push_back(30);

  cout << "myvector contains:";
  for_each (myvector.begin(), myvector.end(), myfunction);

  // or:
  cout << "\nmyvector contains:";
  for_each (myvector.begin(), myvector.end(), myobject);

  cout << endl;

  return 0;
}


Output:
myvector contains: 10 20 30
myvector contains: 10 20 30


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值