如何在c ++中使用带有指针对象向量的find算法?

esr*_*kan 17 c++ algorithm pointers stl vector

我想在匹配对象的Object指针向量中找到它.这是一个示例代码来说明我的问题:

class A {
public:
    A(string a):_a(a) {}
    bool operator==(const A& p) {
        return p._a == _a; 
    }

private: 
    string _a;
};

vector<A*> va;

va.push_back(new A("one"));
va.push_back(new A("two"));
va.push_back(new A("three"));

find(va.begin(), va.end(), new A("two"));
Run Code Online (Sandbox Code Playgroud)

我想找到推入向量的第二个项目.但由于vector被定义为指针集合,C++不使用我的重载运算符,而是使用隐式指针比较.什么是首选的C++ - 在这种情况下解决方案的方式?

Jam*_*kin 17

将find_if与仿函数一起使用:

template <typename T>
struct pointer_values_equal
{
    const T* to_find;

    bool operator()(const T* other) const
    {
        return *to_find == *other;
    }
};


// usage:
void test(const vector<A*>& va)
{
    A* to_find = new A("two");
    pointer_values_equal<A> eq = { to_find };
    find_if(va.begin(), va.end(), eq);
    // don't forget to delete A!
}
Run Code Online (Sandbox Code Playgroud)

注意:您的运算符==对于A应该是const,或者更好的是,将其写为非成员朋友函数.