在指针列表中查找项目

our*_*s84 8 c++ list std find

我试图了解如何使用std :: find在C++中的指针列表中查找项目

如果我有例如:

std::list<string> words;
std::string word_to_be_found;
Run Code Online (Sandbox Code Playgroud)

我可以像这样搜索:

std::list<string>::iterator matching_iter = std::find(words,begin(), words.end(), word_to_be_found)
Run Code Online (Sandbox Code Playgroud)

但是如果我有一些指针呢?

std::list<string *> words;
Run Code Online (Sandbox Code Playgroud)

以上语法将不再起作用.我能以类似的方式做到吗?

谢谢!

R. *_*des 12

您可以将谓词传递给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(), words.end(),
                          std::bind1st(pointee_is_equal, word_to_be_found));
Run Code Online (Sandbox Code Playgroud)

在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;
                     });
Run Code Online (Sandbox Code Playgroud)