C ++ STL's Non-mutating algorithms is a set of template functions that do not destroy operation data, it is used for processing sequence data one by one, element search, subsequence search, statistics, and matching.
For_each is used to traverse container elements one by one. It executes operations defined by the single-Parameter Function object f for each element specified by [first, last) in the iterator range.
Prototype:
View plain
Template <class InputIterator, class Function>
Function for_each (
InputIterator _ First,
InputIterator _ Last,
Function _ Func
);
Note:
In the for_each algorithm range [first, last), each element calls function F and returns the input parameter f. This function does not modify any element in the sequence.
Sample Code:
View plain
/*************************************** ****************************
* Copyright (C) Jerry Jiang
*
* File Name: For_each.cpp
* Author: Jerry Jiang
* Create: 2011-9-27 19:46:44
* Mail: jbiaojerry@gmail.com
* Blog: http://blog.csdn.net/jerryjbiao
*
* Description: A simple program interpreting one of the C ++ STL algorithm series
* Non-variable algorithm: traverse the container element for_each one by one
*
**************************************** **************************/
# Include <algorithm>
# Include <list>
# Include <iostream>
Using namespace std;
// Print is a pseudo-function.
Struct print {
Int count;
Print () {count = 0 ;}
Void operator () (int x)
{
Cout <x <endl;
++ Count;
}
};
Int main (void)
{
List <int> ilist;
// Initialization
For (size_t I = 1; I <10; ++ I)
{
Ilist. push_back (I );
}
// Print and traverse the ilist Element
Print p = for_each (ilist. begin (), ilist. end (), print ());
// Print the number of ilist Elements
Cout <p. count <endl;
Return 0;
}
Example:
Imitation functions, or function objects, are one of the six components (containers, configurators, iterators, algorithms, adapters, and functions) of STL (standard template library; although the imitation function is small, it greatly expands the functions of the algorithm. Almost all algorithms have the imitation function version. For example, the search algorithm find_if is an extension of the find algorithm. The standard search is achieved by two element directions, but what is equal requires different definitions under different circumstances, if the address is equal, the address and the zip code are both equal. Although these definitions are changing, the algorithm itself does not need to be changed, thanks to the imitation function. The function object is called a function object because all the functions are classes that define () function operators.
Author: "Jerry Jiang's program life"