在指针列表中找到一个项目 [英] find an item in a list of pointers
本文介绍了在指针列表中找到一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图理解如何使用std :: find
在C ++中的指针列表中找到一个项目:
std :: list< string>话;
std :: string word_to_be_found;
我可以像这样搜索:
std :: list< string> :: iterator matching_iter = std :: find(words,begin(),words.end(),word_to_be_found)
但是如果我有一个lsit的指针呢?
std :: list< string *>话;
上述语法将不再工作。
解决方案
您可以将谓语传递给
std :: find_if
函数:bool pointee_is_equal(const std :: string& s,const std :: string * p){
return s == * p;
}
// ...
std :: list< string> :: iterator matching_iter =
std :: find_if(words,begin .end(),
std :: bind1st(pointee_is_equal,word_to_be_found));
在C ++ 11中,这变得容易多了,感谢lambdas:
auto matching_iter = std :: find_if(words,begin(),words.end(),
[& word_to_be_found](const std: :string * p){
return word_to_be_found == * p;
});
I am trying to understand how to find an item in a list of pointers in C++, using std::find
If I had for example:
std::list<string> words; std::string word_to_be_found;
I could just search like this:
std::list<string>::iterator matching_iter = std::find(words,begin(), words.end(), word_to_be_found)
but what if I have a lsit of pointers?
std::list<string *> words;
the above syntax will not work anymore. Can I do it some similar way?
thanks!
解决方案You can pass a predicate to the
std::find_if
function:bool pointee_is_equal(const std::string& s, const std::string* p) { return s == *p; } // ... std::list<string>::iterator matching_iter = std::find_if(words,begin(), words.end(), std::bind1st(pointee_is_equal, word_to_be_found));
In C++11 this becomes much easier, thanks to lambdas:
auto matching_iter = std::find_if(words,begin(), words.end(), [&word_to_be_found](const std::string* p) { return word_to_be_found == *p; });
这篇关于在指针列表中找到一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文