STL::for_each用法

std::for_each用法示例:

#include  

#include  

#include  

struct persoan

{

int age;
int degree;
};

// for_each用于对元素操作的仿函数,参数必须为元素的类型,返回值没有要求

void add(persoan& p1)
{
    p1.age += 10;
}


void prt(persoan& p1)
{
printf("age:%d, degree:%d\n", p1.age, p1.degree);
}

void test_for_each()
{
std::vector per_arr;


persoan per;
per.age = 1;
per.degree = 1;
per_arr.push_back(per);

per.age = 4;
per.degree = 4;
per_arr.push_back(per);

per.age = 2;
per.degree = 2;
per_arr.push_back(per);
 
std::for_each(per_arr.begin(), per_arr.end(), add);
std::for_each(per_arr.begin(), per_arr.end(), prt);
}


int main()

{

  test_for_each();

  return 0;

}


result:

age:11, degree:1

age:14, degree:4

age:12, degree:2






你可能感兴趣的:(C/C++)