在指针列表中找到一个项目

编程入门 行业动态 更新时间:2024-10-28 16:18:38
本文介绍了在指针列表中找到一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图理解如何使用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; });

更多推荐

在指针列表中找到一个项目

本文发布于:2023-11-03 07:33:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554579.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   项目   列表中

发布评论

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

>www.elefans.com

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