Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a find function?

Tags:

c++

vector

Trying to define a find function for my vector because the vector holds multiple data; it's a vector of a struct

I'm taking input of an ID, and am trying to search that in my Table and find its index (if that ID already exists)

So I have the declarations here:

vector<Employee> Table;
vector<Employee>::iterator It;
vector<Employee>::iterator find_It;

//Table has these values
//Table.ID, Table.ch1, Table.ch2

And I'm trying to find the ID here:

cin >> update_ID;
find_It = find(Table.begin(), Table.end(), update_ID);

Would there be a way to do the find with the variable update_ID?

I tried doing this:

find_It = find(Table.begin(), Table.end(), (*It).update_ID;

but obviously my vector Employee doesn't have that data member named update_ID

The other option I was thinking of doing is creating my own find function, which I'm a little confused on how to define

I want to return the index of the ID where Table.ID = update_ID

What do I put as the return type and value parameters? Is it

returntype find( Iterator, Iterator, update ID)
{ 
    for (vector<Employee>::iterator myit = Table.begin(), Table.end(), myit++)
    {
        if update_ID == Table.ID
        {
            return myit;
        }
    }
    return myit
}
like image 955
simplycoding Avatar asked Dec 12 '22 20:12

simplycoding


2 Answers

The C++ standard library comes with a set of find functions.

You are looking for find_if which takes a functor that specifies the comparison.

// a functor taking the update_ID you 
// are looking for as an argument in the constructor
struct myfind {
  myfind(int needle) : needle(needle) {}

  int needle;
  bool operator()(const Employee& x) {
    return x.ID == needle;
  }
};

// use as
int update_ID = 23;
std::find_if(begin(Table), end(Table), myfind(update_ID));

You can also use a lambda:

int id;
std::find_if(begin(Table), end(Table),
             [=](const Employee& x) { return x.update_ID == id; });
like image 172
pmr Avatar answered Dec 20 '22 08:12

pmr


The obvious approach is to use std::find_if() with a predicate. Using C++ 2011 notation this could look like so:

std::vector<Employee>::iterator it(std::find_if(Table.begin(), Table.end(),
                                   [=](Employee const& e) { return e.ID == update_ID; });

If you can't use C++ 2011, you can either create a function object for the predicate or use a suitable function with a bound argument for the update_ID.

like image 37
Dietmar Kühl Avatar answered Dec 20 '22 09:12

Dietmar Kühl