【C++ STL学习之六】STL算法之for_each
2012-04-23 20:25
721 查看
for_each()函数将调用者提供的操作施加于每一个元素身上。它既可以是非变动性算法,也可以说是变动性算法。
将函数f施加于区间[first,last)的每一个元素身上。其实现:
f可以是普通函数,也可是仿函数。它的任何返回值都将被忽略。
程序实例:
下面的例子实现了两个功能:
一是使用普通函数print()打印所以元素;而是使用自定义的仿函数来改变每个元素:将每个元素乘以3.
main.cpp:
template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function f);
将函数f施加于区间[first,last)的每一个元素身上。其实现:
template<class InputIterator, class Function> Function for_each(InputIterator first, InputIterator last, Function f) { for ( ; first!=last; ++first ) f(*first); return f; }它返回f已在算法内部变动过的一个副本。
f可以是普通函数,也可是仿函数。它的任何返回值都将被忽略。
程序实例:
下面的例子实现了两个功能:
一是使用普通函数print()打印所以元素;而是使用自定义的仿函数来改变每个元素:将每个元素乘以3.
main.cpp:
#include "algostuff.h" using namespace std; void print(int elem) { cout << elem << " "; } //define a functor //multiply every element with the value initialized template <class T> class MultiplyValue{ private: T value; public: MultiplyValue(const T val):value(val){} //the function call void operator()(T &elem) { elem *= value; } }; int main() { vector<int> intVec; INSERT_ELEMENTS(intVec,1,9); cout << "elements : " << endl; for_each(intVec.begin(),intVec.end(),print); cout << endl << endl; for_each(intVec.begin(),intVec.end(),MultiplyValue<int>(3)); PRINT_ELEMNTS(intVec,"after multiply : "); cout << endl; }algostuff.h:
#ifndef ALGOSTUFF_H #define ALGOSTUFF_H #include <iostream> #include <vector> #include <list> #include <deque> #include <set> #include <map> #include <string> #include <algorithm> #include <functional> #include <numeric> //print all the elements template <class T> inline void PRINT_ELEMNTS(const T &col,const char *optcstr = " ") { typename T::const_iterator pos; cout << optcstr; for(pos = col.begin();pos != col.end();++pos) cout << *pos << " "; cout << endl; } //insert values from first to last into the collection template <class T> inline void INSERT_ELEMENTS(T &col,int first,int last) { for(int i = first;i <= last;++i) col.insert(col.end(),i); } #endif运行结果:
相关文章推荐
- 【C++ STL学习之六】STL算法之for_each
- 【C++ STL学习之六】STL算法之for_each
- C++ STL 学习 :for_each与仿函数(functor)
- C++ STL 学习 :for_each与仿函数(functor)(一)
- C++ STL 中有关于for_each() 和 transform() 算法
- STL学习之十四:常用算法 for_each 和 transform以及adjacent_find的示例代码
- STL算法学习-- for_each( ) 与 transform()
- C++ STL 学习 :for_each与仿函数(functor)
- STL学习笔记----9.STL算法之 for_each()
- c++ 标准模板库 STL 算法之 for_each 函数的使用用法详解
- C++ STL 学习 :for_each与仿函数(functor)(一)
- c++ 标准模板库 STL 算法之 for_each 函数的使用用法详解
- C++ Primer Plus学习笔记之STL算法
- STL与泛型编程<十七>:STL算法简介及for_each()算法
- C++ STL源代码学习之算法篇
- 记录 C++ STL 中 一些好用的函数--持续更新 (for_each,transform,count_if,find_if)
- c++_stl_for_each
- STL常用遍历算法for_each和transform的比较
- STL-fill()填充算法以及for_each()算法
- C++ for_each学习笔记