Archive for October, 2009
A Python sort trick
By chys on October 23rd, 2009>>> a = [12,14,133,130,176,25,54,79,127] >>> b = sorted(range(len(a)),key=a.__getitem__) >>> b [0, 1, 5, 6, 7, 8, 3, 2, 4] >>> map(a.__getitem__,b) [12, 14, 25, 54, 79, 127, 130, 133, 176]
b is the so called sort index.
Reference
http://www.newsmth.net/bbscon.php?bid=284&id=59819
Tags: Python
std::hash<std::string>
By chys on October 4th, 2009TR1 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.
