Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find an item in a list of pointers

Tags:

c++

find

list

std

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!

like image 498
ouroboros84 Avatar asked Jul 21 '11 15:07

ouroboros84


3 Answers

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;
                     });
like image 124
R. Martinho Fernandes Avatar answered Oct 18 '22 16:10

R. Martinho Fernandes


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)
like image 22
Nim Avatar answered Oct 18 '22 15:10

Nim


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

like image 38
Oliver Charlesworth Avatar answered Oct 18 '22 15:10

Oliver Charlesworth