Hash_map in C ++ STL

Source: Internet
Author: User

Hash_map in C ++ STL

When defining a hash_map container, you must specify not only the key and value types, but also the hash and equality functions.

 

(1) hash function of hash_map

 

What does hash <int> look like? Look at the source code:

 
struct hash
 
   { size_t operator()(int __x) const { return __x; } };
 

It turns out to be a function object. In sgi stl, the following hash functions are provided:

struct hash
 
  struct hash
  
   struct hash
   
     struct hash
    
      struct hash
     
      struct hash
      
       struct hash
       
         struct hash
        
          struct hash
         
          struct hash
          
            struct hash
           
          
         
        
       
      
     
    
   
  
 

That is to say, if your key is one of the above types, you can use the default hash function. Of course, you can also define your own hash function. You can only do this for custom variables. For example, for strings, you must customize the hash function. For example:

Struct str_hash {size_t operator () (const string & str) const {unsigned long _ h = 0; for (size_t I = 0; I <str. size (); I ++) _ h = 5 * _ h + str [I]; return size_t (_ h );}}; // if you want to use the system-defined string hash function, you can write: struct str_hash {size_t operator () (const string & str) const {return _ stl_hash_string (str. c_str ());}};

Pay attention to the following points when declaring your own hash function:

  1. Use struct, and then overload operator (). The return value is the type of the size_t parameter which is the key you want to hash. The function is of the const type.

    (2) comparison functions of hash_map

     

    For comparison functions in map, the less function is required. If not, the default value is less <Key>. In hash_map, You need to compare whether the data in the bucket is equal to the key, so you need a function that is equal to or greater than _to <Key>. Let's take a look at the mongo_to source code:

    // This code can look at the binary_function declaration from the sgi stl // first, but it only defines some types. Template
       
        
    Struct binary_function {typedef _ Arg1 first_argument_type; typedef _ Arg2 second_argument_type; typedef _ Result result_type;}; // see the definition of pai_to: template
        
         
    Struct functions _to: public binary_function <_ Tp, _ Tp, bool> {bool operator () (const _ Tp & _ x, const _ Tp & _ y) const {return _ x ==__ y ;}};
        
       

    If you use a custom data type, such as struct mystruct, or const char *, how do you use a comparison function? There are two methods to use the comparison function. The first method is to use the = operator with the overload and use the equal_to; operator. Let's look at the example below:

    struct mystruct{ int iID; int len; bool operator==(const mystruct & my) const{ return (iID==my.iID) && (len==my.len) ; } };

    In this way, you can use performance_to <mystruct> as a comparison function. Another method is to use function objects. Customize a comparison function body:

    struct compare_str{        bool operator()(const char* p1, const char*p2) const{                return strcmp(p1,p2)==0;        }};

    With compare_str, you can use hash_map.

    Typedef hash_map
       
        
    , Compare_str> StrIntMap; StrIntMap namemap; namemap ["Yue Bu Qun"] = "head of Huashan school, called Jun Zijian"; namemap ["Zhang Sanfeng"] = "Wudang manager, founder of Taijiquan "; namemap ["invincible in the east"] = "first master, sunflower Collection ";
       

    (3) how to add a custom type to hash_map?

     

    #include 
       
        #include 
        
         #include 
         
          using namespace std;//define the classclass ClassA{        public:        ClassA(int a):c_a(a){}        int getvalue()const { return c_a;}        void setvalue(int a){c_a;}        private:        int c_a;};//1 define the hash functionstruct hash_A{        size_t operator()(const class ClassA & A)const{                //  return  hash
          
           (classA.getvalue());                return A.getvalue();        }};
          
         
        
       

    //2 define the equal functionstruct equal_A{        bool operator()(const class ClassA & a1, const class ClassA & a2)const{                return  a1.getvalue() == a2.getvalue();        }};int main(){        hash_map
       
         hmap;        ClassA a1(12);        hmap[a1]="I am 12";        ClassA a2(198877);        hmap[a2]="I am 198877";                cout<
        
         

     

     

     

     

     

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.