Reputation: 67211
I am seeing a code where in the program it is creating a hash_map:
// Create a hash_map hm3 with the
// allocator of hash_map hm1
hash_map <MyStr, MyInt>::allocator_type hm1_Alloc;
hm1_Alloc = hm1.get_allocator( );
hash_map <MyStr, MyInt, hash_compare <MyStr, less_str > > hm3( hash_compare <MyStr, less_str > (), hm1_Alloc );
hm3.insert( Int_Pair( "three", 30 ) );
Could anyone please explain me the 3rd statement where hm3 is declared.
hash_map <MyStr, MyInt, hash_compare <MyStr, less_str > > hm3( hash_compare <MyStr, less_str > (), hm1_Alloc );
The complete program can be found here
Upvotes: 1
Views: 239
Reputation: 523184
hash_map <MyStr, MyInt, hash_compare <MyStr, less_str > >
This is a type, being a hash map which maps a MyStr to a MyInt, using a custom hash compare functor type. Let's call it HashMap
.
hash_compare <MyStr, less_str > ()
The syntax T()
creates a temporary object of type T
using the default constructor. The code above constructs the hash compare functor. Let's call this object hashCmp
.
hm1_Alloc
This is a custom allocator.
That declaration can then be rewritten as
typedef hash_compare<MyStr, less_str> HashCmpT;
typedef hash_map<MyStr, MyInt, HashCmpT> HashMap;
HashCmpT hashCmp;
HashMap hm3 (hashCmp, hm1_Alloc);
Upvotes: 1
Reputation: 8387
We create object called hm3. It's class is hash_map <MyStr, MyInt, hash_compare <MyStr, less_str > >
. It (class) is a template class hash_map and this template takes two parameters - two class names. First one is MyStr. Second one is template function hash_compare <MyStr, less_str >
. This (second) template takes also two parametrs. They are MyStr
class and something called less_str
.
Why such template? I suppose first parametr of hash is the container of element. The second one is the function for comparison such containers.
Add:
And about constructor: it takes result of template function smt hash_compare <MyStr, less_str > (void)
and some kind of object.
Add2: It can be shown like this:
typedef hash_map <MyStr, MyInt, hash_compare <MyStr, less_str > > Someclass;
Someotherclass var = hash_compare <MyStr, less_str > (); // `var` is what this function returned
Someclass hm3( var, hm1_Alloc );
Upvotes: 0
Reputation: 73433
It is creating an object of hash_map
named hm3
. Here is my take on the parameters:
Template parameter 1 (MyStr): Key for the map
Template parameter 2 (MyInt): Value for the key
Template parameter 3 : The comparison function to compare two keys. You are using a function called hash_compare
(which again is a template) to do this.
The constructor you are using (2nd one in the MSDN) of the hash_map
class requires an instance of the comparator function and the allocator. You are creating an unnamed (temporary) instance of the function object hash_compare
and passing an allocator hm1_Alloc
to the constructor.
Upvotes: 0