For algorithm inside the function use is not much, but after using to find, before written a lot of redundant code, so intends to learn to use the system of algorithm in the things, this is the first, from algorithm order learning, the first one is for_each.
First look at the definition of For_each:
Template <class _inputiterator, class _function>inline _libcpp_inline_visibility_functionfor_each (_ Inputiterator __first, _inputiterator __last, _function __f) {for (; __first! = __last; +__first) __f (* __first); Return _vstd::move (__f); Explicitly moved for (emulated) c++03}
This is the algorithm header file definition in Xcode, there are two definitions under Windows, _for_each and For_each, the latter in the implementation of the former, so we use the for_each is good.
In this function, you need to be aware that the city function function can only use global function, that is, if the use of class member functions is not possible, of course, static class member functions are OK. When you use a class static member, you must precede the function name with a reference. For example, a function static void printnum (int &num) is defined in class test to print num, then used in For_each:
Vector<int> numbers (ten); Define a capacity of 10vector to store some integers generate (Numbers.begin (), Numbers.end (), []{ return rand ()%100; }); Use the Generate function to assign a vector value to for_each (Numbers.begin (), Numbers.end (), &test::p rintnum),//To make the class test static / /member function as an incoming parameter of the for_each need to add a reference
Of course, if the global function is not necessary, write directly on the line. In addition, this method object in the compiler support C++11, you can use the lambda function, which is much more convenient, such as printing the data inside the vector, you can write:
For_each (Numbers.begin (), Numbers.end (), [] (int &var) { cout<<var<< ""; });
Specific about the For_each parameter function object can refer to the following csdn this article, written very well:
http://blog.csdn.net/yingevil/article/details/6745793
Algorithm Learning Road (i) for_each