4 ms·
Shouldn't this be titled, "use std::find_if where appropriate"? The whole point of this is to find every element in the list which matches the lambda. Which i
by mywittyname 5y ago
Shouldn't this be titled, "use std::find_if where appropriate"?
The whole point of this is to find every element in the list which matches the lambda. Which is why it returns an iterator: you're supposed to use that value, increment it, then call std::find_if again with it as the first parameter.
Granted, the documentation is failing here, since it doesn't provide an example of this use case.
for(auto i = begin(v), e = end(v); find_if(i, e, lambda_func) != e; ++i) {
cout << "Found a match: " << i
}
If you don't need a list of matching elements, but instead want to know if there was any match, then use a different function designed for that specific use.
- kragen 5y agoThat's a valid way to use `find_if`, although you wrote `find_if(i, ` where you meant `i = find_if(`. But I don't think "the whole point" of `find_if` is "to find every element in the list which [fulfills the predicate]". §10 of the STL paper (pp. 41–55) doesn't mention this as a goal of `find_if`, and the result of using `find_if` that way isn't composable with other STL algorithms; for example, you can't use `equal` to compare two such "lists" of matching elements or `unique_copy` to eliminate adjacent duplicates from one of them. If the STL contained something whose "whole point" was "to find every element in the list" which fulfilled the predicate, it would be an iterator adaptor, like Python 2's `itertools.ifilter`, Python 3's `filter`, Boost's `filter_adaptor`, or C++20's `std::ranges::filter_view`. The closest thing in the STL is `copy_if`, which is happy to take an output iterator for its destination parameter, for example a `back_insert_iterator`.