The hash container unordered_map in C++ is used as an example

  • 2020-04-02 03:06:37
  • OfStack

With the establishment of the C++0x standard, there was finally a hash table in the C++ standard library.

For a long time, the STL provided only < The map > As a container to store corresponding relations, the internal is usually implemented with red-black tree, it is said that the reason is that various operations of binary balance tree (such as red-black tree), insert, delete, search, etc., are stable time complexity, that is, order (log n); However, in the case of hash, the performance problems caused by re-hash cannot be avoided, even though the performance of the hash is very good in most cases, the instability caused by re-hash is intolerable at that time.

However, due to the performance advantages of hash tables, it is still widely used, so third-party libraries, such as MSVC, are basically supported < hash_map > And the Boost of < Boost/unordered_map HPP > . Boost's unordered_map was then absorbed into TR1 (C++ Technical Report 1) and was eventually standardized in C++0x.

So now we can happily write the following code:


#include <iostream>
#include <string>
#include <unordered_map>
 
int main()
{
 std::unordered_map<std::string, int> months;
 months["january"] = 31;
 months["february"] = 28;
 months["march"] = 31;
 months["april"] = 30;
 months["may"] = 31;
 months["june"] = 30;
 months["july"] = 31;
 months["august"] = 31;
 months["september"] = 30;
 months["october"] = 31;
 months["november"] = 30;
 months["december"] = 31;
 std::cout << "september -> " << months["september"] << std::endl;
 std::cout << "april   -> " << months["april"] << std::endl;
 std::cout << "december -> " << months["december"] << std::endl;
 std::cout << "february -> " << months["february"] << std::endl;
 return 0;
}


Related articles: