简体   繁体   中英

find an item in a list of pointers

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM