[英]How to use find algorithm with a vector of pointers to objects in c++?
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"));
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.
但是由于将vector定义为指针集合,因此C ++不使用我的重载运算符,而是使用隐式指针比较。 What is the preferred C++-way of solutiono in this situation?
在这种情况下,首选的C ++解决方案方式是什么?
Use find_if with a functor: 将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!
}
Note: your operator== for A ought to be const, or, better still, write it as a non-member friend function. 注意:A的运算符==应该是const,或者最好将其编写为非成员好友函数。
Either use std::find_if and provide a suitable predicate yourself, see other answers for an example of this. 可以使用std :: find_if自己提供一个合适的谓词,有关其他示例,请参见其他答案。
Or as an alternative have a look at boost::ptr_vector , which provides transparent reference access to elements which are really stored as pointers (as an extra bonus, memory management is handled for you as well) 或者,可以看一下boost :: ptr_vector ,它提供了对实际上存储为指针的元素的透明引用访问(作为额外的好处,还可以为您处理内存管理)
Try using find_if instead. 尝试改用find_if。 It has a parameter for a predicate where you can decide exactly how to check wheter you found the right element.
它有一个谓词参数,您可以在其中精确决定如何检查是否找到了正确的元素。
http://www.sgi.com/tech/stl/find_if.html http://www.sgi.com/tech/stl/find_if.html
You could also use Boost::Lambda: 您还可以使用Boost :: Lambda:
using namespace boost::lambda;
find_if(va.begin(), va.end(), *_1 == A("two"));
Of course, you should prefer to use shared_ptrs so you don't have to remember to delete! 当然,您应该更喜欢使用shared_ptrs,这样就不必记住要删除!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.