17

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

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"));

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

4

4 回答 4

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!
}

注意:A 的 operator== 应该是 const,或者,更好的是,将其写为非成员友元函数。

于 2008-11-03T15:03:05.423 回答
4

要么使用 std::find_if 并自己提供合适的谓词,请参阅其他答案以获取此示例。

或者作为替代方案查看boost::ptr_vector,它提供对真正存储为指针的元素的透明引用访问(作为额外的奖励,内存管理也为您处理)

于 2008-11-03T15:05:30.583 回答
1

尝试改用 find_if 。它有一个谓词参数,您可以在其中准确决定如何检查是否找到了正确的元素。

http://www.sgi.com/tech/stl/find_if.html

于 2008-11-03T14:59:43.433 回答
1

你也可以使用 Boost::Lambda:

using namespace boost::lambda;
find_if(va.begin(), va.end(), *_1 == A("two"));

当然,您应该更喜欢使用 shared_ptrs,这样您就不必记住删除!

于 2008-11-04T12:23:25.840 回答