Boost logo

Boost Users :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2003-08-25 14:34:00


On Monday 25 August 2003 07:05 am, Darren Cook wrote:
> class Info{
> public:
> int key;
> std::set<int> points;
> };
>
> class InfoContainer{
> public:
> Info* get(int);
> };
>
> void grab_keys(const InfoContainer &cs,const Info *c){
> std::set<int> list;
> std::set<int>::const_iterator i=c->points.begin();
> while(i!=c->points.end()){
> Info *ec=cs.get(*i++);
> list.add(ec->key);
> //Previous two lines could be written: list.add(cs.get(*i++)->key);
> }
> //Do something with list here.
> }

grab_keys2 would look like this:

void grab_keys2(const AllInfo &cs,const Info *c){
Points list;
std::for_each(c->points.begin(),c->points.end(),
        boost::bind(&Points::add,
                boost::bind(&Info::key,
                        boost::bind(&InfoContainer::get, &cs, _1))));

However, if Points is std::set<int>, then "add" should be "insert" and you
have a problem because std::set<int>::insert is overloaded. So let's look at
what you're trying to do:

You want to map each elements of points to an "Info" pointer via
InfoContainer, access the 'key' element through that Info pointer, and put
all of those 'key' elements into a std::set, right? Well, that's a
transformation on the original sequence of points, so use std::transform like
this:

void grab_keys3(InfoContainer& cs, const Info* c) {
  std::set<int> list;
  std::transform(c->points.begin(), c->points.end(),
          std::inserter(list, list.end()),
          boost::bind(&Info::key, boost::bind(&InfoContainer::get, &cs, _1)));
}

        Doug


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