find an item in a list of pointers

末鹿安然 提交于 2019-12-22 04:17:25

问题


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!


回答1:


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;
                     });



回答2:


Provide your own predicate:

struct comparator
{
  bool operator()(std::string const* item)
  {
    return toFind == *item;
  }
  std::string toFind;
};

comparator cinst = { word_to_find };
std::list<string*>::iterator matching_iter = std::find_if(words,begin(), words.end(), cinst)



回答3:


You want to use std::find_if() instead, and supply it a functor to do the comparisons.



来源:https://stackoverflow.com/questions/6778218/find-an-item-in-a-list-of-pointers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!