我对std::find
的界面感到困惑。为什么不用Compare
对象来告诉它如何比较两个对象?如何使用比较对象std :: find?
如果我能通过一个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"
谢谢!出于好奇,“copy_if”有什么问题? – Frank 2010-04-17 02:33:33
@dehmann:唯一错的是它不在标准中。基本上由于编辑事故而被排除在外。 – 2010-04-17 02:34:37