Click to See Complete Forum and Search --> : Map and Functor :: STL


kuphryn
November 25th, 2002, 10:35 PM
Hi.

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


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

proxima centaur
November 25th, 2002, 11:00 PM
You want a function object.

You have to define a "parenthesis" operator.

so you would do something like:


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/pgi/pgC++_lib/stdlibug/fun_0476.htm

kuphryn
November 25th, 2002, 11:38 PM
Christian of CodeProject mentioned that the iterator returns a pair object. For example:


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

Paul McKenzie
November 26th, 2002, 03:15 AM
Originally posted by kuphryn
Christian of CodeProject mentioned that the iterator returns a pair object. For example:


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

kuphryn
November 26th, 2002, 09:32 AM
Nice! Thanks.

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


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