在对象向量上使用find

编程入门 行业动态 更新时间:2024-10-23 17:34:26
在对象向量上使用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);

更多推荐

本文发布于:2023-07-23 02:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226539.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   对象   find

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!