我想在对象指针的向量中查找匹配的对象。下面是一个示例代码来说明我的问题:
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++解决方案是什么?
发布于 2008-11-03 15:03:05
将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-03 15:05:31
或者使用std::find_if并自己提供合适的谓词,请参阅其他答案以获取有关此问题的示例。
或者作为另一种选择,看看boost::ptr_vector,它提供了对真正存储为指针的元素的透明引用访问(作为额外的好处,还为您处理了内存管理)。
发布于 2008-11-03 14:59:43
请尝试使用find_if。它有一个用于谓词的参数,您可以在其中准确地决定如何检查是否找到了正确的元素。
https://stackoverflow.com/questions/258871
复制相似问题