如何使用查找算法指针的向量对象在C ++? [英] How to use find algorithm with a vector of pointers to objects in c++?
问题描述
我想找到的对象指针的匹配对象的向量。下面是一个示例code来说明我的问题:
I want to find in a vector of Object pointers for a matching object. Here's a sample code to illustrate my problem:
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"));
我想找到第二个项目推入载体。但是,由于矢量被定义为一个指针集合,C ++不使用我的重载运算符,但使用隐式指针比较。什么是preferred C ++ - solutiono在这种情况下,这样
I want to find the second item pushed into the vector. But since vector is defined as a pointers collection, C++ does not use my overloaded operator, but uses implicit pointer comparison. What is the preferred C++-way of solutiono in this situation?
推荐答案
使用find_if一个函子:
Use find_if with a functor:
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应该是const,或者更好的是,写它作为一个非成员友元函数
Note: your operator== for A ought to be const, or, better still, write it as a non-member friend function.
这篇关于如何使用查找算法指针的向量对象在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!