CPP/STL/ForEach

From ProgrammingExamples
< CPP
Revision as of 23:37, 6 July 2010 by FirstPerson (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
#include <iostream>
#include <algorithm>
#include <vector>
 
using namespace std;
 
void showSquaredValue(const int n){ 	
	cout  <<  n << "*" << n  << " = " << n*n << endl; 
};
 
class RepeatSequence{
	int begin, end;
	int offset;
public:
	RepeatSequence(int first, int last): begin(first),end(last - 1), offset(begin - 1){}
	RepeatSequence(): begin(),end(), offset(){}
	int operator()(){
		return offset = offset >= end ? begin: offset + 1;
	}
};
 
int main(){
 vector<int> num;
 const int MAX = 10;
 
 std::generate_n(std::back_insert_iterator<vector<int>>( num ),
		 MAX,
		 RepeatSequence(0,5)
		);
 
 //for each values in the vector num, show its squared value 
 std::for_each(num.begin(),num.end(),showSquaredValue);
 
  return 0;
}