Question

Could not easily find a solution online...

I have something similar to the following.

class Color {
  public:
    Color(std::string n) : name(n) {}
    typedef std::tr1::shared_ptr<Color> Ptr;
    std::string name;
 };

meanwhile elsewhere...

void Function()
{
    std::vector<Color::Ptr> myVector;
    Color::Ptr p1 = Color::Ptr(new Color("BLUE") );
    Color::Ptr p2 = Color::Ptr(new Color("BLUE") );

    // Note: p2 not added.
    myVector.push_back( p1 );

    // This is where my predicament comes in..
    std::find( myVector.begin(), myVector.end(), p2 );
}

How would I write this so my std::find would actually deference the smart_pointers and compare the objects strings rather than their memory addresses? My first approach was to write a custom std::equal function however it does not accept templates as its own template types.

Was it helpful?

Solution

Easiest may be to use find_if:

template <typename T>
struct shared_ptr_finder
{
    T const & t;

    shared_ptr_finder(T const & t_) : t(t_) { }

    bool operator()(std::tr1::shared_ptr<T> const & p)
    {
        return *p == t;
    }
};

template <typename T>
shared_ptr_finder<T> find_shared(std::tr1::shared_ptr<T> const & p)
{
    return shared_ptr_finder<T>(*p);
}

#include <algorithm>

typedef std::vector< std::tr1::shared_ptr<Color> >::iterator it_type;
it_type it1 = std::find_if(myVector.begin(), myVector.end(), find_shared(p2));
it_type it2 = std::find_if(myVector.begin(), myVector.end(), shared_ptr_finder<Color>(*p2));

OTHER TIPS

You can implement:

bool operator==(Color::Ptr const & a, Color::Ptr const & b);

Or, you could use std::find_if and implement a predicate that would function how you want.

In C++11, it could look something like:

std::find_if( myVector.begin(), myVector.end(), [&](Color::Ptr & x) { return *p2 == *x });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top