通过代码来学习for_each()的使用方法,代码如下:
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
using namespace std;
template <class Type>
class MultValue
{
private:
Type Factor;
public:
MultValue ( const Type& _Val ) : Factor ( _Val ) {
}
void operator ( ) ( Type& elem ) const
{
elem *= Factor;
}
};
class Average
{
private:
long num;
long sum;
public:
Average ( ) : num ( 0 ) , sum ( 0 )
{
}
void operator ( ) ( int elem )
{
num++;
sum += elem;
}
operator double ( )
{
return static_cast <double> (sum) /
static_cast <double> (num);
}
};
template<class TYPE>
void increment(TYPE&X)
{
X++;
}
int main(int argc,_TCHAR* argv[])
{
using namespace std;
vector <int> v1;
vector <int>::iterator Iter1;
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;
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;
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;
double avemod2 = for_each ( v1.begin ( ) , v1.end ( ) ,
Average ( ) );
cout << "The average of the elements of v1 is:\n Average ( v1mod2 ) = "
<< avemod2 << "." << endl;
int nums[] = {3, 4, 2, 9, 15, 267};
const int N = 6;
cout << "Before, nums[] is: ";
for( int i = 0; i < N; i++ ) {
cout << nums[i] << " ";
}
cout << endl;
for_each( nums, nums + N, increment<int> );
cout << "After, nums[] is: ";
for( int i = 0; i < N; i++ ) {
cout << nums[i] << " ";
}
cout << endl;
return 0;
}
责任编辑:小草