Boost logo

Boost Users :

Subject: Re: [Boost-users] for_each on boost::ptr_map
From: Robert Jones (robertgbjones_at_[hidden])
Date: 2008-09-16 10:15:35


On Tue, Sep 16, 2008 at 3:00 PM, Peter Barker <newbarker_at_[hidden]> wrote:
> On Mon, Sep 15, 2008 at 9:20 PM, Robert Dailey <rcdailey_at_[hidden]> 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
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> 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.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net