为什么有些STL算法提供了额外的'_if'功能而不是重载它?
// example:
find(beg, end, val);
find_if(beg, end, pred);
Run Code Online (Sandbox Code Playgroud)
难道他们只是重载这些算法而不是制作额外的_if功能吗?
我对界面感到困惑std::find.为什么不用一个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;
Run Code Online (Sandbox Code Playgroud)
以下是推荐的方法吗?
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 = …Run Code Online (Sandbox Code Playgroud)