for_each( InputIterator beg, InputInterator end, UnaryProc op)
- 对区间[beg, end)中的每一个元素调用:op(elem);
- op的任何返回值都会被忽略
- 复杂度:线性。
使用仿函数来改变每一个元素内容。
#include <print.hpp>
using namespace std;
template<class T>
class AddValue{
private:
T theValue;
public:
AddValue(const T& v): theValue(v){}
void operator() (T& elem)const{
elem+=theValue;
}
};
int main()
{
vector<int> coll;
INSERT_ELEMENTS(coll,1,9);
for_each(coll.begin(),coll.end(),AddValue<int>(10));
PRINT_ELEMENTS(coll);
for_each(coll.begin(),coll.end(),AddValue<int>(*coll.begin()));
PRINT_ELEMENTS(coll);
}
