Posts Tagged ‘STL’

std::hash<std::string>

TR1 requires std::tr1::hash (std::hash in C++0x) to be instantiable for integer/floating point types, std::string and std::wstring. (C++0x added std::error_code, std::thread:id, std::bitset, std::u16string, std::u32string, and std::vector<bool>.)

But for strings, every call to std::hash<string>::operator()(std::string) incurs an unnecessary copy construction, which can be expensive in implementations where std::basic_string does not use COW.

Developers of GCC are apparently aware of this, and they added specializations std::hash<const std::string &> and std::hash<const std::wstring &> starting from GCC 4.3.

However, I still guess we cannot easily benefit from this since we will need to write something like this:

std::unordered_set<std::string, std::hash<const std::string &>>

(In C++0x it’s no longer required to insert a space between the two larger-than characters.)

Too ugly and inconvenient to use, unless our program is really time critical.

Tags: , , ,