C++陈述分析
我看到程序中正在创建 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 ) );
任何人都可以向我解释声明 hm3 的第三条语句吗?
hash_map <MyStr, MyInt, hash_compare <MyStr, less_str > > hm3( hash_compare <MyStr, less_str > (), hm1_Alloc );
完整的程序可以在此处找到
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种类型,是一个哈希映射,使用 自定义哈希比较函子类型。我们将其称为
HashMap
。语法
T()
使用默认构造函数创建一个T
类型的临时对象。上面的代码构造了哈希比较函子。我们将此对象称为hashCmp
。这是一个自定义分配器。
该声明可以重写为
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
.The syntax
T()
creates a temporary object of typeT
using the default constructor. The code above constructs the hash compare functor. Let's call this objecthashCmp
.This is a custom allocator.
That declaration can then be rewritten as
它正在创建一个名为
hm3
的hash_map
对象。以下是我对参数的看法:模板参数 1 (MyStr):地图的键
模板参数 2 (MyInt):键的值
模板参数 3:用于比较两个键的比较函数。您正在使用一个名为
hash_compare
的函数(它又是一个模板)来执行此操作。您正在使用的
hash_map
类的构造函数(MSDN 中的第二个)需要比较器函数和分配器的实例。您正在创建函数对象hash_compare
的未命名(临时)实例,并将分配器hm1_Alloc
传递给构造函数。It is creating an object of
hash_map
namedhm3
. 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 objecthash_compare
and passing an allocatorhm1_Alloc
to the constructor.我们创建名为 hm3 的对象。它的类是 hash_map
; >
。它(类)是一个模板类 hash_map,该模板采用两个参数 - 两个类名。第一个是 MyStr。第二个是模板函数hash_compare
。这个(第二个)模板也有两个参数。它们是MyStr
类和名为less_str
的东西。为什么要这样的模板?我想哈希的第一个参数是元素的容器。第二个是比较此类容器的功能。
添加:
关于构造函数:它获取模板函数
smt hash_compare 的结果; (void)
和某种对象。添加2:
可以这样显示:
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 functionhash_compare <MyStr, less_str >
. This (second) template takes also two parametrs. They areMyStr
class and something calledless_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: