在对象向量上使用find_if(Using find_if on a vector of objects)
我没有使用boost库。 我怎么能用STL做到这一点?
class Files { private: bool isSame(FileID f1, FileId f2) { if(f1.getId()==f2.getId()) return true; return false; } public: vector<FileId> mod_files; void update() { FildId f = getFileId(); vector<FildId>::const_iterator found = find_if(mod_files.begin(), mod_files.end(), ???); } };我想将isSame作为find_if函数的第三个参数传递,并将“f”绑定到isSame的第二个参数。
I am not using boost libraries. How can i do this using STL?
class Files { private: bool isSame(FileID f1, FileId f2) { if(f1.getId()==f2.getId()) return true; return false; } public: vector<FileId> mod_files; void update() { FildId f = getFileId(); vector<FildId>::const_iterator found = find_if(mod_files.begin(), mod_files.end(), ???); } };I would like to pass isSame as the third argument to find_if function, and bind "f" to the isSame's second argument.
最满意答案
在C ++ 11中简单地说:
std::bind(&Files::isSame, this, f);在旧的C ++ 03中 ,没有mem_fun需要2个参数,所以你必须自己进行绑定:
class is_same_pred { public: // unary function typedefs explicit is_same_pred(Files& files, FileId f1) : _files(files), _f1(f1) {} bool operator()(FileId f2) const { return _files.isSame(_f1, f2); } private: Files& _files; FileId _f1; };isSame可以访问is_same_pred ,以后可以像这样使用它:
is_same_pred(this, f);所有这一切,你最好将isSame定义为静态或自由函数 :
bool isSame(FileId f1, FileId f2){ ... } std::bind1st(std::ptr_fun(&isSame), f);In C++11 that's simply:
std::bind(&Files::isSame, this, f);In good old C++03 there is no mem_fun that takes 2 arguments, so you would have to do the binding on your own:
class is_same_pred { public: // unary function typedefs explicit is_same_pred(Files& files, FileId f1) : _files(files), _f1(f1) {} bool operator()(FileId f2) const { return _files.isSame(_f1, f2); } private: Files& _files; FileId _f1; };Where isSame is accessible to is_same_pred, and later use it like this:
is_same_pred(this, f);All that said and done, you would be better off defining isSame as a static or free-function:
bool isSame(FileId f1, FileId f2){ ... } std::bind1st(std::ptr_fun(&isSame), f);更多推荐
发布评论