Franz
Franz

Reputation: 245

Using find_if - How to include current item in predicate?

I have a <list> of objects of class Reservation. Each Reservation object holds a pointer to a Customer object and a Bike object.

What I'd like to know is: Is there a Reservation for a certain Customer in the <list>? I have one of Customer's attributes, the phone_number to identify the customer.

I tried to achieve that via find_if but I don't know if or how I can access the object that is currently being checked by find_if.

pseudo-code:

found = (find_if(begin, end, iterator→customer→phonenumber == phone_number), != end)

current approach:

    bool found = (find_if(reservation_list.begin(), reservation_list.end(), customer->get_phone_number() == telefonnummer) != res_list.end());

The customer->get_phone_number() part is nonsense as it refers to a customer object pointer declared a few lines above, but not the current iterator.

Thanks!

Upvotes: 1

Views: 90

Answers (1)

ramsay
ramsay

Reputation: 3845

You could use a lambda function to check if there is a Reservation for a certain Customer in the <list> by comparing the phone_number

std::string telefonnummer ="";
auto is_target = [&telefonnummer](const Reservation &reservation) {
  return reservation.customer->get_phone_number() == telefonnummer;
};

bool found = (find_if(reservation_list.begin(), reservation_list.end(),
                      is_target) != res_list.end());

Upvotes: 2

Related Questions