
On Tue, Sep 16, 2008 at 3:00 PM, Peter Barker
On Mon, Sep 15, 2008 at 9:20 PM, Robert Dailey
wrote: Hi,
Is there a way I can use std::for_each() on a boost::ptr_map and have the functor object be given the *value* of each item iterated instead of a key/value pair like it does with std::map? Help is appreciated, thank you.
std::for_each() with std::map receives the pair so you need something like the following to extract the value:
#include <algorithm> #include <iostream> #include <map> #include <string>
#include
class MyClass { public: MyClass(int x) : x_(x) {} int getX() const {return x_;} private: int x_; };
void func(MyClass* mc) { std::cout << mc->getX() << std::endl; }
int main() { typedef std::mapstd::string,MyClass* MapType; MapType myPtrMap;
std::string key1 = "Key1"; std::string key2 = "Key2"; myPtrMap.insert(std::make_pair(key1,new MyClass(1))); myPtrMap.insert(std::make_pair(key2,new MyClass(2))); std::for_each(myPtrMap.begin(),myPtrMap.end(),boost::bind(&func,boost::bind(&MapType::value_type::second,_1))); }
Here's the same code working with ptr_map:
#include <algorithm> #include <iostream> #include <string>
#include
#include class MyClass { public: MyClass(int x) : x_(x) {} int getX() const {return x_;} private: int x_; };
void func(MyClass* mc) { std::cout << mc->getX() << std::endl; }
int main() { typedef boost::ptr_mapstd::string,MyClass MapType; MapType myPtrMap;
std::string key1 = "Key1"; std::string key2 = "Key2"; myPtrMap.insert(key1,new MyClass(1)); myPtrMap.insert(key2,new MyClass(2)); std::for_each(myPtrMap.begin(),myPtrMap.end(),boost::bind(&func,boost::bind(&MapType::value_type::second,_1))); }
I hope that helps you out.
Regards,
Pete _______________________________________________ Boost-users mailing list Boost-users@lists.boost.org http://lists.boost.org/mailman/listinfo.cgi/boost-users
At risk of sounding a complete wally, I have completely failed to understand why the second version is any way preferrable to the first. Why would you want to do this? - Rob.