AutoHotkey Homepage AutoHotkey Community
Let's help each other out
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Help with Advanced C++ Problem: Functors

 
Post new topic   Reply to topic    AutoHotkey Community Forum Index -> General Chat
View previous topic :: View next topic  
Author Message
kjmneel



Joined: 28 Jul 2005
Posts: 9
Location: San Diego, CA

PostPosted: Wed Mar 15, 2006 5:04 am    Post subject: Help with Advanced C++ Problem: Functors Reply with quote

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.

Code:


#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.
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    AutoHotkey Community Forum Index -> General Chat All times are GMT
Page 1 of 1

 
Jump to:  
You can post new topics in this forum
You can reply to topics in this forum


Powered by phpBB © 2001, 2005 phpBB Group