The use of C + + STL Hash_map and the large "pit" of STL Hash_map

Source: Internet
Author: User

The hash table is often used in computer programming, and in C + +, STL programming is indispensable. This article describes the use of Hash_map in STL, the method of using custom types as key values in Hash_map, and the problems encountered when using char * types as key values. First, the required header files and namespaces under Linux use STL Hash_map to reference its namespace in addition to referencing its header file 1 using namespace __gnu_cxx;Second, the definition of hash_map first to see how hash_map is defined:
 1  template<class  _key, class  _tp, class  _HASHFN = hash<_key> ,  2  class  _equalkey = equal_to<_key> , class  _alloc = allocator<_tp> >3  class   hash_map  4   { 5  //  content definition  6 } 

The _key of course is the keyword of the hash you use. Use it to uniquely identify a hash node. _TP is a class of node content that is stored in a hash. _HASHFN is a hash function of Hash_map, which uses hash<key> as the default template function, which is explained in detail later. _equalkey is a hash matching function, and the default is to use the system-defined equal_to, which is explained in detail later. The _alloc is the space Configurator for the container. This is not the focus of this article discussion, in this article I realize the Imitation source code implementation of a spatial configuration of its, inside the note is very detailed, interested can see the next http://www.cnblogs.com/zxtp/p/4975888.html.

If you want to write using the Hash_map container, you should define this:

1 hash_map<int, int> hash;

Of course, the _key and _TP parameters can also be any type you want, including strings, structs, classes, and so on. Just need you to do something more (more on this later). Several types are supported by default in Hash_map:

Char, char *, const char *, unsigned char, signed char, short, unsigned short, int, unsigned int, long, unsignd long.

This means that you do not need to do any other work when you use these types as parameters.

There are three ways to insert in Hash_map, which is to encapsulate it in the form of an object. As follows:

1     hash[; 2     Hash.insert (hash_map<intint>::value_type ()); 3     Hash.insert (pair<intint> ());

Iii. operations commonly used in HASH_MAP (the following code is the example of a hash table created)

1), in the Hash_map query operation, as follows:

1 Hash_map<int, int>::iterator it;    Create an iterator variable 2 it = Hash.find (+);                      Query the table for a key value of 100 for node  3 if (it = Hash.end ())                        {5     cout << "has this element" << endl;6                    } 

2), there are many operations in the Hash_map, this is only said to find, this is because this article will be used to find. Other operations, many examples on the web, do not repeat the work here.

  

Iv. How do I use other custom parameter types as keys?

How do I use other types as key parameters in a hash? In Hash_map, if you want to use your own defined type as the key value of the hash, you need to implement its hash function and matching function. Both the hash function and the comparison function are overloads of the Operator "()", but the contents of the overloads are different. Specific examples are as follows:

In page memory management, if you need to get the contents of a piece of memory, you need two of the amount: one is the number of memory pages, and the other is the offset of the page. Suppose there is a request for memory, and the two quantities to be used as the key words of the hash table, as long as you give these two quantities I can index to the specific location of memory. I can use the following structure as the key value of Hash_map.

1 struct Stindex 2 {3public:4     int uipage; // Memory Pages 5     int Uioffset; // The offset on the page 6 };

Then you need to overload the hash function, note that this format is fixed, you have to write this, or write in a class that is defined, encapsulated in a class. The implementation is as follows:

 1  //  2  struct   Sthash  3  { 4  size_t operator  () (const  stindex& key) const   { 6  return  Key.uipage;//  Here I only use one of the fields as its hash basis  7  }  8 }; 

The hash function here is actually not a hash function in the real sense, because after the hash_map, a modulo operation is done.

You also need to overload the comparison function. The format is the same as above, and is also fixed.

1 //Hash Key value comparison function, overloaded "()"2 structStequalkey3 {4     BOOL operator()(Conststkey& Key1,Conststkey& Key2)Const5     {6         returnKey1.uipage = =Key2.uipage7&& Key1.uioffset = =Key2.uioffset;8     }9};

The preparation is complete and now you can use the custom type as the key value for the hash. Just need to specify the hash function and the comparison function that you overloaded. Define as follows:

1 hash_map<stindex, void *vppointer, sthash, stequalkey> hash;

The rest of the operation is the same, this is not the case.

Five, hash_map of a big "pit"!

Why do you think this is a big "pit"? Please be patient and look down!

In Hash_map, you may have the following definitions:

hash_map<charstring> Hash; // the content here uses a string to distinguish between char *

This definition is not wrong, as mentioned earlier, HASH_MAP supports char * Type as the key value. But when used, there are some unexpected problems. As follows:

1 CharPszkey[] ="ABC";2 stringsvalue ="CDEFG";3HASH[PSZSTR] = svalue;//inserted into the hash and inserted into the4 5hash_map<Char*,string>:: iterator it;6it = Find ("ABC");//I can't find what I just inserted.7 8it = find (Pszkey);//to find out what you just inserted.

Why does this happen? The comparison function in Hash_map is implemented in this way:

 1  template <class  _tp>2  struct  equal_to: public  binary _FUNCTION<_TP, _TP, bool  >3   { 4  bool  5  operator  () (const  _tp& __x , const  _tp& __y) const  6  {return  __x == __y;}  7 }; 

Here we can see that its comparison template function passed in the type is the first parameter passed in when creating hash_map, that is to say we write

1 hash_map<Char *,string > hash;

When the parameter is defined in order to a char * type address, in the overloaded function passed in only an address, that is, char * type parameters, when compared, compared to the address only. So it = Find ("abc"); This way, the lookup is not found. If you must use char * as key in your program, only the comparison function is overloaded. And this is not used in the STL to explain. Perhaps the STL's intention is that the address type is not supported.

The use of C + + STL Hash_map and the large "pit" of STL Hash_map

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.