代码之家  ›  专栏  ›  技术社区  ›  Vijay

C++语句分析

  •  1
  • Vijay  · 技术社区  · 14 年前

       // 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 ) );
    

    谁能给我解释一下hm3的第三个声明吗。

    hash_map <MyStr, MyInt, hash_compare <MyStr, less_str > > hm3( hash_compare <MyStr, less_str > (), hm1_Alloc );
    

    here

    3 回复  |  直到 14 年前
        1
  •  1
  •   kennytm    14 年前
    hash_map <MyStr, MyInt, hash_compare <MyStr, less_str > >
    

    这是一个类型,是一个哈希映射,它使用 custom hash compare functor type . 我们就叫它吧 HashMap .

    hash_compare <MyStr, less_str > ()
    

    语法 T() T 使用默认构造函数。上面的代码构造了hash compare函子。我们称这个物体为 hashCmp .

    hm1_Alloc
    

    然后可以将该声明改写为

    typedef hash_compare<MyStr, less_str>     HashCmpT;
    typedef hash_map<MyStr, MyInt, HashCmpT>  HashMap;
    
    HashCmpT hashCmp;
    
    HashMap hm3 (hashCmp, hm1_Alloc);
    
        2
  •  0
  •   Naveen    14 年前

    hash_map 命名 hm3 . 以下是我对参数的看法:

    模板参数1(MyStr):映射的键

    hash_compare (这也是一个模板)这样做。

    哈希映射 类需要 比较器函数和分配器。您正在创建函数对象的未命名(临时)实例 哈希\u比较 传递一个分配器 hm1_Alloc 给建造师。

        3
  •  0
  •   Ben Usman    14 年前

    我们创建了一个名为hm3的对象。它的类是哈希图 <MyStr, MyInt, hash_compare <MyStr, less_str > > . 它(类)是一个模板类哈希映射,这个模板有两个参数-两个类名。第一个是MyStr。二是模板函数 hash_compare <MyStr, less_str > . 这个(第二个)模板还需要两个参数。他们是 MyStr less_str .

    为什么是这样的模板?我假设hash的第一个参数是元素的容器。第二个是比较这些容器的功能。

    关于构造函数:它接受模板函数的结果 smt hash_compare <MyStr, less_str > (void)

    地址2: 可以这样表示:

    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 );