CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Feb 2002
    Posts
    5,757

    Map and Functor :: STL

    Hi.

    How do you define a functor that handles elements in an STL map? For example:

    Code:
    std::map<int, char *> testMap;
    
    char *testChar = new char[10];
    _strcpy(testChar, "November");
    
    testMap.insert(std::pair<int, char *>(0, testChar));
    
    ...
    
    // Now I want to deallocate all values in testMap.
    
    std::for_each(testMap.begin(), testMap.end(), DeleteValue());
    How do you define DeleteValue functor that handles elements in an STL map?

    Thanks,
    Kuphryn

  2. #2
    Join Date
    May 2002
    Location
    Quebec City, Canada
    Posts
    374
    You want a function object.

    You have to define a "parenthesis" operator.

    so you would do something like:

    Code:
    struct delete_value
    {
        bool operator() ( int value )
        {
             // do stuff...
           return true; // or false
        }
    };

    I've only defined functors for evaluating lower_than operations on "custom" objects... I dunno about deleting...

    See this page for more info:

    http://www.ccd.bnl.gov/bcf/cluster/p...g/fun_0476.htm
    Martin Breton
    3D vision software developer and system integrator.

  3. #3
    Join Date
    Feb 2002
    Posts
    5,757
    Christian of CodeProject mentioned that the iterator returns a pair object. For example:

    Code:
    class DeleteValue 
    {
       public:
          void operator()(std::pair<int, char *> pairObject)
          {
             // How do you use the pairObject?
          }
    };
    How do you identify with a pair object?

    Kuphryn

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449
    Originally posted by kuphryn
    Christian of CodeProject mentioned that the iterator returns a pair object. For example:

    Code:
    class DeleteValue 
    {
       public:
          void operator()(std::pair<int, char *> pairObject)
          {
             // How do you use the pairObject?
          }
    };
    How do you identify with a pair object?

    Kuphryn
    pairObject.first -- This is the int
    pairObject.second -- This is the char *

    Regards,

    Paul McKenzie

  5. #5
    Join Date
    Feb 2002
    Posts
    5,757
    Nice! Thanks.

    Here is one answer by Joaqu*n M López Muñoz of CodeProject.

    Code:
    class DeleteValue : public std::unary_function<std::pair<int const,char *>&, void>
    {
       public: 
          void operator()(std::pair<int const,char *> &pairObject)
          {
             delete [] pairObject.second;
          } 
    };
    Kuphryn

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured