
On Mon, Sep 15, 2008 at 9:20 PM, Robert Dailey <rcdailey@gmail.com> 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 <boost/bind.hpp> 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::map<std::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 <boost/bind.hpp> #include <boost/ptr_container/ptr_map.hpp> 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_map<std::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