Detailed usage of for_each function in STL algorithm of C ++ standard template library

Source: Internet
Author: User
Tags print print

STD: for_each

template <class InputIterator, class Function>   Function for_each (InputIterator first, InputIterator last, Function fn);
Apply function to range

Applies FunctionFNTo each of the elements in the range[first,last).

The behavior of this template function is equivalent:

123456789
template<class InputIterator, class Function>  Function for_each(InputIterator first, InputIterator last, Function fn){  while (first!=last) {    fn (*first);    ++first;  }  return fn;      // or, since C++11: return move(fn);}




Parameters
First, last
Input iterators to the initial and final positions in a sequence. The range used is [first,last), Which contains all the elements FirstAnd Last, Including the element pointed FirstBut not the element pointed Last.
FN
Unary function that accepts an element in the range as argument.
This can either be a function pointer or a move constructible function object.

Its return value, if any, is ignored.

Applies a specified function object to each element in a forward order within a range and returns the function object.

template<class InputIterator, class Function>    Function for_each(       InputIterator _First,        InputIterator _Last,        Function _Func    );
Parameters

_ First

An input iterator addressing the position of the first element in the range to be operated on.

_ Last

An input iterator addressing the position one past the final element in the range operated on.

_ FUNC

User-Defined Function object that is applied to each element in the range.

Return Value

A copy of the function object after it has been applied to all of the elements in the range.

Remarks

The algorithm for_each is very flexible, allowing the modification of each element within a range in different, user-specified ways. templatized functions may be reused in a modified form by passing different parameters. user-defined functions may accumulate information within an internal state that the algorithm may return after processing all of the elements in the range.

The range referenced must be valid; All pointers must be dereferenceable and, within the sequence, the last position must be reachable from the first by incrementation.

The complexity is linear with at most (_ last-_ First) comparisons.

 

Header file:

<Algorithm>

Note:

In the for_each algorithm range [_ first, _ last), each element calls function _ fn1 and returns the input parameter _ FUNC. This function does not modify any element in the sequence.

 

// For_each example # include <iostream> // STD: cout # include <algorithm> // STD: for_each # include <vector> // STD :: vector # include <list> void myfunction (int I) {// function: STD: cout <''<I;} struct myclass {// function object type: void operator () (int I) {STD: cout <''<I ;}} myobject; void test_my () {STD: vector <int> myvector; myvector. push_back (10); myvector. push_back (20); myvector. push_back (30); STD: cout <"myvector contains:"; for_each (myvector. begin (), myvector. end (), myfunction); STD: cout <'\ n'; // or: STD: cout <"myvector contains:"; for_each (myvector. begin (), myvector. end (), myobject); STD: cout <'\ n'; STD: cout <"myvector contains:"; for_each (myvector. begin (), myvector. end (), myclass (); STD: cout <'\ n';}/***** running result: myvector contains: 10 20 30 myvector contains: 10 20 30 myvector contains: 10 20 30 ****** // print is the imitation function struct print {int count; print () {COUNT = 0 ;} void operator () (int x) {STD: cout <x <STD: Endl; ++ count ;}}; void test_print () {using namespace STD; list <int> testlist; // initialize for (size_t I = 1991; I <2013; ++ I) {testlist. push_back (I);} // traverse the testlist element and print Print P = for_each (testlist. begin (), testlist. end (), print (); // print the number of testlist elements. cout <"the number of elements is:" <p. count <Endl;}/****** running result: the number of 1991199219931994199519961997199819992000200120022003200420052006200720082009201020112012 elements is: 22 ******/class multi_by_x {PRIVATE: int multiplier; public: multi_by_x (const Int & K): multiplier (k) {} void operator () (const Int & X) {STD :: cout <x * multiplier <"" <STD: Endl ;}}; void test_multi_by_x () {int sequence [6] ={ 2007,2010, 2011,2012, 2007,2014 }; using STD: vector; vector <int> V (sequence, sequence + 6); multi_by_x multi2 (2); for_each (v. begin (), V. end (), multi2); // apply function}/*************** running result: 401440204022402440264028 *************/INT main () {test_my (); STD :: cout <"\ n ********************************** * **************** \ n "; test_print (); STD :: cout <"\ n ********************************** * **************** \ n "; test_multi_by_x (); STD :: cout <"\ n ********************************** * **************** \ n "; return 0;}/*************** myvector contains: 10 20 30 myvector contains: 10 20 30 myvector contains: 10 20 30 ************************************* * ************* the number of elements is as follows: 22 *************************************** *************************** * ********************** process returned 0 (0x0) execution time: 0.039 spress any key to continue. ****************/

Let's take a look at the example program provided above msdn.
:

 

 

# Include <vector> # include <algorithm> # include <iostream> // The function object multiplies an element by a factortemplate <class type> class multvalue {PRIVATE: type factor; // The value to multiply bypublic: // constructor initializes the value to multiply by multvalue (const type & _ Val): factor (_ Val) {}// the function call for the element to be multiplied void operator () (type & ELEM) con St {ELEM * = factor ;}}; // The function object to determine the averageclass average {private: Long num; // The number of elements long sum; // The sum of the elementspublic: // constructor initializes the value to multiply by average (): num (0), sum (0) {}// the function call to process the next elment void operator () (int elem) {num ++; // increment the element count sum + = ELEM ;// Add the value to the Partial Sum} // return average operator double () {return static_cast <double> (SUM)/static_cast <double> (Num );}}; int main () {using namespace STD; vector <int> V1; vector <int>: iterator iter1; // constructing vector V1 int I; for (I =-4; I <= 2; I ++) {v1.push _ back (I) ;}cout <"original vector V1 = ("; for (iter1 = v1.begin (); iter1! = V1.end (); iter1 ++) cout <* iter1 <"; cout <"). "<Endl; // using for_each to multiply each element by a factor for_each (v1.begin (), v1.end (), multvalue <int> (-2 )); cout <"multiplying the elements of the vector V1 \ n" <"by the factor-2 gives: \ n v1mod1 = ("; for (iter1 = v1.begin (); iter1! = V1.end (); iter1 ++) cout <* iter1 <"; cout <"). "<Endl; // The function object is templatized and so can be // used again on the elements with a different factor for_each (v1.begin (), v1.end (), multvalue <int> (5); cout <"multiplying the elements of the vector v1mod \ n" <"by The Factor 5 gives: \ n v1mod2 = ("; for (iter1 = v1.begin (); iter1! = V1.end (); iter1 ++) cout <* iter1 <"; cout <"). "<Endl; // the local state of a function object can accumulate // information about a sequence of actions that the // return value can make available, here the average double avemod2 = for_each (v1.begin (), v1.end (), average (); cout <"the average of the elements of V1 is: \ n average (v1mod2) = "<avemod2 <". "<Endl;}/******************* the running result is as follows: original vector V1 = (-4-3-2-1 0 1 2 ). multiplying the elements of the vector V1 by the factor-2 gives: v1mod1 = (8 6 4 2 0-2-4 ). multiplying the elements of the vector v1mod by the factor 5 gives: v1mod2 = (40 30 20 10 0-10-20 ). the average of the elements of V1 is: Average (v1mod2) = 10. process returned 0 (0x0) execution time: 0.122 spress any key to continue. ******************/

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.