Boost logo

Boost Users :

From: Tom Matelich (tmatelich_at_[hidden])
Date: 2003-04-11 15:43:01


> From: dick.bridges_at_[hidden] [mailto:dick.bridges_at_[hidden]]
> Sent: Friday, April 11, 2003 11:54 AM
>
> This is probably more of a C++ than an boost question but, since it
> involves shared_ptr, I thought I'd try it here first. I've
> got a vector of
> shared_ptrS (e.g., vector<shared_ptr<T> > v;) and I need to
> find the entry
> given the 'real' pointer to the underlying T. Looping thru
> the vector like
> this:
>
> <snippet>
> for( vector<shared_ptr<T>::iterator itr = v.begin(); itr !=
> v.end(); itr++)
> {
> if( itr->get() == real_this){...}
> }
> </snippet>
>
> works but seems klunky. I should be able to use [find_if(
> v.begin(), v.end
> (), ???)] but I can't work out the predicate. Any help or
> "pointers" ;)
> will be greatly appreciated.
>
Here's how I like to do it, though my co-workers sometimes complain:

#include "boost/shared_ptr.hpp"
#include "boost/bind.hpp"
#include <vector>
#include <iostream>

int main()
{
  typedef std::vector<boost::shared_ptr<int> > V;
  V vec;
  int* foo = new int;
  vec.push_back(boost::shared_ptr<int>(foo));
  
  V::iterator iter = std::find_if(vec.begin(), vec.end(),
                       boost::bind(std::equal_to<int*>(),
                         boost::bind(&boost::shared_ptr<int>::get, _1),
                                 foo));

  if(iter != vec.end())
    std::cout << "Life is good" << std::endl;
        
  //don't delete foo!!!

  return 0;
}

Tom

-----------------------------------------------------------------------
DISCLAIMER: Information contained in this message and/or
attachment(s) may contain confidential information of Zetec, Inc.
If you have received this transmission in error, please notify
the sender by return email.
-----------------------------------------------------------------------


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