STL——for_eachの使い方


説明:
template <class InputIterator, class Function>
   Function for_each (InputIterator first, InputIterator last, Function f);

Apply function to range
Applies function 
f
 to each of the elements in the range  [first,last)
.
The behavior of this template function is equivalent to:
1
2
3
4
5
6
template<class InputIterator, class Function>
  Function for_each(InputIterator first, InputIterator last, Function f)
  {
    for ( ; first!=last; ++first ) f(*first);
    return f;
  }


例1-for_eachの使い方
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
using namespace std;

class GenByTwo {
	public:
		GenByTwo (int _seed = 0):seed(_seed){}
		int operator() () {return seed += 2;}

	private:
		int seed;
};

void operate(int &rhs)
{
	cout << rhs << " ";
	rhs += 1;
}
int main(int argc, char* argv[])
{
	vector<int> v(10);
	generate(v.begin(), v.end(), GenByTwo(2));
	for_each(v.begin(), v.end(), operate);

	//print
	copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));

	return 0;
}

例2:単語の出現回数を統計する
#include <iostream>
#include <string>
#include <map>
#include <fstream>
#include <algorithm>
#include <ctime>
using namespace std;


map<string , int> m;
void print( const pair<string, int> &r)
{
		cout << r.first << "   " << r.second << endl;
}
void record( const string &s)
{
		m[ s ] ++;
}
int main()
{
	double beginTime = clock();
	fstream in("source.txt");
	istream_iterator<string> ii(in);
	istream_iterator<string>eos;
	for_each(ii,eos,record);
	for_each( m.begin(), m.end(), print);
	double endTime = clock();

	cout << " time: " << endTime - beginTime << " ms" << endl;
	return 0;
}