如何将查找算法与指向 c++ 中对象的指针向量一起使用?
我想在对象指针向量中找到匹配对象。 这是一个示例代码来说明我的问题:
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++不使用我的重载运算符,而是使用隐式指针比较。 在这种情况下,首选的 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. What is the preferred C++-way of solutiono in this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将 find_if 与仿函数一起使用:
注意:A 的运算符 == 应该是 const,或者更好的是,将其编写为非成员友元函数。
Use find_if with a functor:
Note: your operator== for A ought to be const, or, better still, write it as a non-member friend function.
要么使用 std::find_if 并自己提供合适的谓词,请参阅其他答案以获取相关示例。
或者作为替代方案,请查看 boost::ptr_vector ,它提供对真正存储为指针的元素的透明引用访问(作为额外的好处,内存管理也为您处理)
Either use std::find_if and provide a suitable predicate yourself, see other answers for an example of this.
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)
尝试使用 find_if 代替。 它有一个谓词参数,您可以在其中准确决定如何检查是否找到了正确的元素。
http://www.sgi.com/tech/stl/find_if.html
Try using find_if instead. 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
你也可以使用Boost::Lambda:
当然,你应该更喜欢使用shared_ptrs,这样你就不必记住删除!
You could also use Boost::Lambda:
Of course, you should prefer to use shared_ptrs so you don't have to remember to delete!