template <>
Function for_each (InputIterator first, InputIterator last, Function f);
对范围[first, last]内的每一个元素调用函数f。
这个模版函数的行为跟下述代码类似:
template
Function for_each(InputIterator first, InputIterator last, Function f)
{
while ( first!=last )
f(*first++);
return f;
}
参数:
first, last
对应序列中最初位置和最后位置的输入迭代器。其适用范围是[first, last]包含在first和last之间的所有元素,包括由first指向的元素,但是不包括last指向的元素。
F
将范围中一个元素作为参数的一元函数。这可以一个函数指针,也可以是类中重载了操作符()的类对象。
返回值
跟f的返回值相同。
示例:
// for_each example
#include
#include
#include
using namespace std;
void myfunction (int i)
{ cout << " " <<> 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 <<>
#include
#include
using namespace std;
struct print {
void operator()(const int& i)
{ cout << n =" 5;"> iv(input, input+N);
for_each(iv.begin(), iv.end(), &printfun);
cout << endl;
}
输出:
for_each
1,2,3,4,5,
1,2,3,4,5,
复杂度:
线性复杂度:仅对每个元素使用一次函数f
1 件のコメント:
Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my blog, it is about the Wireless, I hope you enjoy. The address is http://wireless-brasil.blogspot.com. A hug.
コメントを投稿