2024-03-21

Algorithms header knowledge check

Note some late additions marked with *.

* After posting this I began to feel it needed a little bit more detail. And then that it needed quite a bit more detail.


The C++ standard library's algorithm header has a routine sutiable for counting the number of places of disagreement between two equal sized collections of elements. What's it called? Hint: it's not called "count_differences". *Nor is it called count_if (unless you happen to be using C++-23 because count_if doesn't have an overload for parallel containers.0) My work projects are in C++-17 and my home projects in'17 or '20.

Answer
inner_product

*One approach is to write a "sum" function that adds just as in the usual inner product, but the make the one that would do element multiplication in the standard inner produt return zero when the two values are equal and one if they differ.

For that matter, what educational backgrounds would prepare you to recognize that as the routine you want?1 How does this compare to Kate Gregory's story about partial_sort_copy and how it would be better called top_n?


*0 C++23 doesn't introduce a parallel overload either, but it does introduce zip_view and zip which will allow you to efficiently produce on single container of apparent pairs from the parallel containers. Then you can use the single-container version of count_if. Obvious. Right?

1 My combination of physics and prior experience with the algorithm header's love affair with having a user-supplied-predicate-to-change-the-behavior overload meant that I spotted it as soon as I read the name, but ... that's a rather esoteric requirement for user's to know what they're seeing.

No comments:

Post a Comment