📅  最后修改于: 2020-10-16 09:13:35             🧑  作者: Mango
C++ STL algorithm.for_each()函数将函数func应用于从“第一个”到“最后一个”范围内的所有元素。
template
Function for_each (InputIterator first, InputIterator last, Function func);
first:它指定列表中的第一个元素。
last:它指定列表中的最后一个元素。
func:这是一元函数,它接受范围内的参数。
该函数返回“ func”。
#include
#include
#include
void newfunction (int k)
{
std::cout << " " < newvector;
newvector.push_back(50);
newvector.push_back(100);
newvector.push_back(150);
std::cout << "newvector contains:\n";
for_each (newvector.begin () , newvector.end (), newfunction);
std::cout<< "\n newvector contains:\n";
for_each (newvector.begin (), newvector.end(), newfunction);
std::cout<<"\n";
return 0;
}
输出:
newvector contains: 50 100 150
newvector contains: 50 100 150
#include
#include
#include
using namespace std;
void printx1(int b)
{
cout << b * 2 << " ";
}
struct Class1
{
void operator() (int b)
{
cout << b * 3 << " ";
}
} obj1;
int main()
{
int ar[5] = { 6, 7, 8, 9, 10 };
cout << "Using Arrays:" << endl;
cout << "Multiple of 2 of elements are : ";
for_each(ar, ar + 5, printx1);
cout << endl;
cout << "Multiple of 3 of elements are : ";
for_each(ar, ar + 5, obj1);
cout << endl;
vector ar1 = { 2,3,5,7,1 };
cout << "Using Vectors:" << endl;
cout << "Multiple of 2 of elements are : ";
for_each(ar1.begin(), ar1.end(), printx1);
cout << endl;
cout << "Multiple of 3 of elements are : ";
for_each(ar1.begin(), ar1.end(), obj1);
cout << endl;
}
输出:
Using Arrays:
Multiple of 2 of elements are : 12 14 16 18 20
Multiple of 3 of elements are : 18 21 24 27 30
Using Vectors:
Multiple of 2 of elements are : 4 6 10 14 2
Multiple of 3 of elements are : 6 9 15 21 3
该函数以线性方式移动,从第一个元素到最后一个元素。对于列表中的每个元素,都会检查“ pred”的值。搜索一直进行到与“ pred?”不匹配为止。遇到价值。
函数可以访问指定范围内的所有对象,也可以访问其中的一些对象。
如果任何参数抛出一个异常,该函数将引发异常。