9 ms·
Replace std:find_if in 80% of the cases
- deleted 5y ago[deleted]
- sillysaurusx 5y agoIs "using namespace std" still considered heresy? I rather liked it. It'd make a lot of these examples a little more readable.
- riskneutral 5y agoI don't like it, clarity is better in C++. Things are complicated enough as it is.
- kragen 5y agoHow about `using std::find_if`?
- dataflow 5y agoUnqualified calls change the behavior. You end up doing ADL instead of a normal lookup and could potentially end up calling a different function than the one you intended entirely. Sometimes that's intentional (as with swap), but often it's a bug.
- sillysaurusx 5y agoI've been a C++ dev for longer than I care to admit. The idea that you could call the wrong function after putting "using std::string" at the top of your .cpp file doesn't reflect my experience. You might have a point if people are putting that in header files. But even in header files, "using std::string" is often a standard thing to do in e.g. game engines. It's far easier to change out your string implementation if you're writing "string" instead of "std::string".
- dataflow 5y ago> using std::string The question was about find_if, which is a function, not string.
- deleted 5y ago[deleted]
- eska 5y agoDefinitely don't use it in headers, because it pollutes the namespace of files including it. In .cpp files it's more subjective. You can also resort to only using it in functions, to limit it's scope to code where you make heavy use of std.
- yellow_lead 5y ago> So I went through all our usages of find_if and I found that it was only used in a proper way in about 20% of all the cases. > This means that the Pareto principle applies here too. In 80% of the cases, std::find_if should not have been used. I don't think this is the pareto principle. Its a rule of probabilities, i.e 1-X.
- tomjakubowski 5y agoThe Pareto principle can be stated thus: When the percentage sign's 89 minus nine That's Pareto
- kragen 5y agoAgreed. 80% of the `find_if` cases require 20% of the what, exactly? The functions? But he's using four times as many functions now.
- toxik 5y agoMarginally more readable, but is it performing better?
- twoodfin 5y agoIndeed, outside of corner cases where iterators are expensive to copy or compare, I’d be surprised if there were any measurable advantage beyond clarity.
- secondcoming 5y agoNo, the codegen is the same https://godbolt.org/z/eebE9eYP6 https://godbolt.org/z/eebE9eYP6
- felixguendling 5y agoWhen reading the title I thought that it is about complexity of linear search vs. better alternatives like hash sets/maps, or at least sorted data structures (binary search). But if having linear complexity is fine, std::find_if/any_of/none_of/all_of/etc. are of course fine and you should prefer the version that's most expressive.
- kragen 5y agoOf course; as Larry Wall said, doing a sequential search over the keys of a hash table is like clubbing someone to death with a loaded Uzi.
- mywittyname 5y agoIt's safer, more reliable, and easier to clean up after?
- Zababa 5y agoI doubt it will be safer and more reliable unless the person doesn't fight back. I do agree for cleanup, especially if the bullets go through.
- malkia 5y agoWondering if something like this can catch these - https://twitter.com/_fel1x/status/1443613096820543492 https://twitter.com/_fel1x/status/1443613096820543492
- kragen 5y agoReading these I'm struck by the non-orthogonality and "mental compilation" on display here. In Python instead of return numbers.end() != std::find_if(numbers.begin(), numbers.end(), [](int number) { return number % 2 == 1; }); I would write return any(number % 2 == 1 for number in numbers) which, similarly, stops examining numbers once it finds an odd one, but works by transforming the sequence of numbers into a lazy sequence of booleans, then applying the generic boolean-sequence-reducer `any` to it. I think this more clearly says what is desired (the C++ version strikes me as something a compiler might output given the Python version, but in this case you had to run the compiler in your mind), and additionally is a better orthogonal decomposition of the problem than computing a first-hit iterator from a sequence of numbers and a number-to-boolean transformation, then comparing it against the end of the sequence. Sandor's suggested replacement solves the first problem of clearly saying what is desired: return std::any_of(numbers.begin(), numbers.end(), [](int number) { return number % 2 == 1; }); But the penalty is even worse orthogonality! Because of Python's better orthogonality, you can factor out the lazy boolean sequence generator into a function of its own if that's a useful thing to do: def oddnesses(numbers): return (number % 2 == 1 for number in numbers) return any(oddnesses(numbers)) In this particular case the extra degree of composability you get from it is not very useful, but then again, neither is the original code. You could do things like this with that sequence with equal plausibility to the original code: all(oddnesses(numbers)) # addressed by all_of in OP zip(numbers, oddnesses(numbers)) sum(oddnesses(numbers)) # punning booleans as ints sum(map(operator.mul, numbers, oddnesses(numbers))) Of course, Python is not really a viable alternative to C++ in most of the places where people are using C++, mostly because it uses 40 times as much CPU and energy and 10 times as much memory, but also because large Python codebases get unmaintainable. But we could wish for a language with the efficiency and in-the-large maintainability of C++ and the clarity and generality of Python.
- eska 5y agoAre you aware of ranges? std::ranges::any_of(numbers, [](auto i){ return i % 2 == 0; })) There's also stuff like this for orthogonality https://en.cppreference.com/w/cpp/ranges/transform_view https://en.cppreference.com/w/cpp/ranges/transform_view
- mywittyname 5y agoShouldn'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`.
- deleted 5y ago[deleted]
- quietbritishjim 5y agoI disagree with the article's conclusion. The evidence in it proves that it's better not to use the specialised functions (like any_of). It's immediately clear to me what each of the find_if snippets does, but I haven't heard of the other functions – and the evidence from the article is that the vast majority of other programmers haven't either (in fact that's out of the subset that bother to use find_if, which I would say means even less of general coders). Sure, it's fairly obvious what they do from the name, but I'd still bother to check their signature in case there's a subtlety. In other words, there may be fewer lines of code, but it's still more cognitive overhead. In fact I'd go one step further and say it's better to use raw primitives, like for loops (range based where appropriate), where they don't need too much extra code.
- leetcrew 5y agoit seems like your argument boils down to "I prefer a for loop because I'm more familiar with it". if that's true of you and most of the people you work with, that's certainly a valid argument. the opposite happens to be true on my team. we understand and prefer the functions from the algorithms header in most cases. one argument in favor of functions like any_of is that, once you get familiar with them, they provide additional documentation of intent. I'll concede this is a pretty minor benefit; most uses of any_of replace a pretty simple loop.
- quietbritishjim 5y ago> it seems like your argument boils down to "I prefer a for loop because I'm more familiar with it". I don't think that's it. A lot of code ends up being calls to functions, and so other types of syntax add a bit of texture. Replacing those with function calls too reduces the code to a smooth paste. It's a bit like if the standard library had a lessThanThree(x) function; it doesn't matter how totally familiar I was with it, I'd still prefer to see x<3.
- josephcsible 5y agotl;dr: if the only thing you do with the result of find_if or find_if_not is compare it to .end(), then you should use all_of, any_of, or none_of instead.