Heterogeneous comparison comparator

We have a heterogeneous search in C ++ 14. I wonder why the default comparator for a map, set, etc. Has not been changed to less than <>. Without this change, the average C ++ user completely skips this function and slows down the search for const char * in set <string> still there. I have seen this circuit too many times in my codebase. Even MS revealed that this was a real bottleneck in one of their GoingNative videos. I can suspect that code violation was a problem, but I don’t see how this could happen for code that already worked in C ++ 98/11

+6
source share
1 answer

Consider:

struct Foo { bool operator<(const Foo&) const;}; struct Bar { operator Foo() const; }; std::set<Foo> s; Bar b; s.find(b); 

By default, s uses std::less<Foo> , and s.find() takes const Foo & , so lookup creates one temporary Foo from Bar and uses it for all comparisons.

In contrast, if s were changed to the transparent comparison functor std::less<> , then in combination with heterogeneous search, each comparison in find() will be between a Foo and a Bar , so each comparison will build a temporary Foo . This is a silent performance degradation.

+9
source

Source: https://habr.com/ru/post/976894/


All Articles