Using generate to generate values for all elements of chars with custom function - C++ STL Algorithm

C++ examples for STL Algorithm:generate_n

Description

Using generate to generate values for all elements of chars with custom function

Demo Code

#include <iostream> 
#include <algorithm> // algorithm definitions 
#include <vector> // vector class-template definition 
#include <iterator> // ostream_iterator 
using namespace std; 

char nextLetter(); // prototype of generator function 

int main() //from  w  ww. jav a  2 s .  c o m
{ 
   vector< char > chars( 10 ); 
   ostream_iterator< char > output( cout, " " ); 
   fill( chars.begin(), chars.end(), '5' ); // fill chars with 5s 

   cout << "Vector chars after filling with 5s:\n"; 
   copy( chars.begin(), chars.end(), output ); 


   // generate values for all elements of chars with nextLetter 
   generate( chars.begin(), chars.end(), nextLetter ); 

   cout << "\n\nVector chars after generating letters A-J:\n"; 
   copy( chars.begin(), chars.end(), output ); 

   // generate values for first five elements of chars with nextLetter 
   generate_n( chars.begin(), 5, nextLetter ); 

   cout << "\n\nVector chars after generating K-O for the" 
       << " first five elements:\n"; 
   copy( chars.begin(), chars.end(), output ); 
   cout << endl; 
}

// generator function returns next letter (starts with A) 
char nextLetter() 
{ 
   static char letter = 'A'; 
   return ++letter; 
} // end function nextLetter

Result


Related Tutorials