|
-
November 25th, 2002, 11:35 PM
#1
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
-
November 26th, 2002, 12:00 AM
#2
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.
-
November 26th, 2002, 12:38 AM
#3
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
-
November 26th, 2002, 04:15 AM
#4
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
-
November 26th, 2002, 10:32 AM
#5
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|