How to std::find using a Compare object?
        Posted  
        
            by dehmann
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by dehmann
        
        
        
        Published on 2010-04-16T23:35:15Z
        Indexed on 
            2010/04/16
            23:43 UTC
        
        
        Read the original article
        Hit count: 370
        
I am confused about the interface of std::find. Why doesn't it take a Compare object that tells it how to compare two objects? 
If I could pass a Compare object I could make the following code work, where I would like to compare by value, instead of just comparing the pointer values directly: 
typedef std::vector<std::string*> Vec;
Vec vec;
std::string* s1 = new std::string("foo");
std::string* s2 = new std::string("foo");
vec.push_back(s1);
Vec::const_iterator found = std::find(vec.begin(), vec.end(), s2);
// not found, obviously, because I can't tell it to compare by value
delete s1;
delete s2;
Is the following the recommended way to do it?
template<class T>
struct MyEqualsByVal {
  const T& x_;
  MyEqualsByVal(const T& x) : x_(x) {}
  bool operator()(const T& y) const {
    return *x_ == *y;
  }
};
// ...
vec.push_back(s1);
Vec::const_iterator found = 
    std::find_if(vec.begin(), vec.end(),
                 MyEqualsByVal<std::string*>(s2)); // OK, will find "foo"
© Stack Overflow or respective owner