find an item in a list of pointers

一个人想着一个人 提交于 2019-12-05 04:11:57

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.

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