find an item in a list of pointers
I am trying to understan开发者_JS百科d 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.
精彩评论