【发布时间】:2010-04-16 23:35:15
【问题描述】:
我对@987654321@的界面感到困惑。为什么不使用Compare 对象来告诉它如何比较两个对象?
如果我可以传递一个Compare 对象,我可以使以下代码工作,我想按值进行比较,而不是直接比较指针值:
typedef std::vector<std::string*> Vec;
Vec vec;
std::string* s1 = new std::string("foo");
std::string* s2 = new std::string("foo");
vec.push_back(s1);
Vec::const_iterator found = std::find(vec.begin(), vec.end(), s2);
// not found, obviously, because I can't tell it to compare by value
delete s1;
delete s2;
以下是推荐的方法吗?
template<class T>
struct MyEqualsByVal {
const T& x_;
MyEqualsByVal(const T& x) : x_(x) {}
bool operator()(const T& y) const {
return *x_ == *y;
}
};
// ...
vec.push_back(s1);
Vec::const_iterator found =
std::find_if(vec.begin(), vec.end(),
MyEqualsByVal<std::string*>(s2)); // OK, will find "foo"
【问题讨论】:
标签: c++ stl vector find compare