我對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