cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

(almost) always do this with std::map!

Open lefticus opened this issue 4 months ago • 3 comments

std::map<key, value, std::less<>> to easily enable transparent comparators

lefticus avatar Aug 28 '25 21:08 lefticus

What happens if you do it with a key type of std::string and you try to .find("raw string literal") by accident instead of .find("string view literal"sv)? Does it try to construct a std::string for every comparison, or does it just miss out on the optimization of checking the length first before checking the string content? Does it even matter?

LB-- avatar Aug 29 '25 17:08 LB--

what about std::unordered_map with std::hash<> and std::equal_to<>? and also the other containers using hashes and keys?

FalcoGer avatar Sep 03 '25 01:09 FalcoGer

What happens if you do it with a key type of std::string and you try to .find("raw string literal") by accident instead of .find("string view literal"sv)? Does it try to construct a std::string for every comparison, or does it just miss out on the optimization of checking the length first before checking the string content? Does it even matter?

Yes, the point here is to avoid creating the extra strings, because the std::less<> has templated arguments and will compare anything comparable without forcing it into one type or the other.

lefticus avatar Sep 08 '25 20:09 lefticus