Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

Help with Advanced C++ Problem: Functors


  • Please log in to reply
No replies to this topic
kjmneel
  • Members
  • 9 posts
  • Last active: Jan 30 2006 10:52 PM
  • Joined: 28 Jul 2005
Here is a problem that I would like some help with...

This code snippet is meant as a demonstration of functors. The for_each template function will iterate through a container and call the functor for each item in the container. Please fill in the details for the for_each template function.

#include <iostream>

#include <vector>

#include <list>

 

//This template should call the functor once for each item in the container //It should stop if the functor returns false //And it should return the total number of times the functor was called

 

template <class CONTAINER, class FUNCTOR> long for_each(CONTAINER& Container, FUNCTOR& functor)

      {



       //fill in this function

            

      }

 

//This template functor will output the string value of each item passed to it.  It is assumed that the item passed to it had a c_str() method.  The constructor needs the output stream object used to output the strings to.

 

template<class ITEM>

class clsOutput

{

      std::ostream& outputs;

      public:

     

      clsOutput(std::ostream& outputs):outputs(outputs){}

 

      bool operator()(const ITEM& Item)

            {

             outputs << Item.c_str() << std::endl;

             return true;

            }

};

 

int main()

{

      std::vector<std::string> Vector;

      std::list<std::string> List;

 

      Vector.push_back("TEST");

      Vector.push_back("ME");

 

      Vector.push_back("FOR");

      Vector.push_back("ERRORS");

 

 

      for_each(Vector, clsOutput<std::string>(std::cout));

      for_each(List, clsOutput<std::string>(std::cout));

 

}

 

The output of the program should be

 

TEST

ME

FOR

ERRORS



Thanks.