2

Functions such as std::find_if from the algorithm header are really useful, but 1 serious limit for me is the fact that I can only use 1 predicate for each call to count_if.

For example given a container like an std::vector I would like to apply, at the same time, with the same iteration of find_if, multiple predicates; there is something in the standard library that makes this possible while keeping this functional approach ?

user2485710
  • 9,451
  • 13
  • 58
  • 102

1 Answers1

8

Just combine them with a lambda:

std::find_if(begin(vec), end(vec),
    [](elem_t val) {
        return f1(val) || f2(val);
    });
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • oh, it's much simpler than what I expected – user2485710 Dec 24 '13 at 04:30
  • but with this approach the results for different predicates end up going in the same output, what if I would like to dispatch the result to a specific object for each predicate ? – user2485710 Dec 24 '13 at 04:34
  • @user2485710 - to do that you write your own algorithm. – Pete Becker Dec 24 '13 at 04:39
  • @user2485710: it's probably easiest to use `std::copy_if` for each distinct destination, but that involves multiple passes over the source container so it might be more efficient to use a `for` loop with `if (predicate1(val)) dest1.push_back(val); else if ...` lambda. (If you care about performance, always benchmark with your data.) – Tony Delroy Dec 24 '13 at 04:43
  • @user2485710: I'm not sure what you mean. What output? The results of the predicates go to the algorithm for its decision making process about what to do. In the case of `find_if`, that means either terminating if the result is `true`, or continuing on if the result is `false`. Do you have a concrete example of the kind of thing you want to do? Because I may have a solution. – Benjamin Lindley Dec 24 '13 at 09:59
  • @BenjaminLindley you have a person that does the job for you and you give him: 1 container, 3 predicates, 3 buckets, 1 algorithm ( `find`, or `copy`, or ... ), and only 1 chance to iterate over the container; so you have to apply 3 predicates at each container position, at the same time, and each predicate has its own bucket to store the result. – user2485710 Dec 24 '13 at 10:27
  • @user2485710 and what if a single element satisfies more than 1 predicate? do you want to copy it to all the corresponding buckets? – TemplateRex Dec 26 '13 at 13:45
  • @TemplateRex each predicate only refers to 1 single bucket, so yes, if the predicate is `true`, pass the result to the associated bucket. – user2485710 Dec 26 '13 at 13:58