问题描述
最近,我在一本非常著名的书"算法简介".我还没有在任何实际的应用程序中使用它们,但是想要.但是我不知道如何开始.
谁能给我一些使用它的示例,例如,如何使用哈希表实现字典应用程序(例如ABBYY Lingvo)?
最后,我想知道PHP中的哈希表和关联数组之间的区别是什么,我的意思是我应该使用哪种技术以及在哪种情况下使用?
如果我错了(请原谅),请纠正我,因为实际上我是从哈希表开始的,并且我对哈希表只有基本的(理论上的)知识.
非常感谢.
Recently I have read about hash-tables in a very famous book "Introduction to Algorithms". I haven't used them in any real applications yet, but want to. But I don't know how to start.
Can anyone give me some samples of using it, for example, how to realize a dictionary application (like ABBYY Lingvo) using hash-tables?
And finally I would like to know what is the difference between hash-tables and associative arrays in PHP, I mean which technology should I use and in which situations?
If I am wrong (I beg pardon) please correct me, because actually I am starting with hash-tables and I have just basic (theoretical) knowledge about them.
Thanks a lot.
推荐答案
在PHP中,关联数组被实现为哈希表,并具有一些额外的功能.
In PHP, associative arrays are implemented as hashtables, with a bit of extra functionality.
但是,从技术上讲,关联数组与哈希表并不相同-它只是实现的一部分,其背后是哈希表.由于其大多数实现都是哈希表,因此它可以完成哈希表可以执行的所有操作-但它也可以执行更多操作.
However technically speaking, an associative array is not identical to a hashtable - it's simply implemented in part with a hashtable behind the scenes. Because most of its implementation is a hashtable, it can do everything a hashtable can - but it can do more, too.
例如,您可以使用for循环遍历关联数组,而哈希表无法做到这一点.
For example, you can loop through an associative array using a for loop, which you can't do with a hashtable.
因此,尽管它们相似,但关联数组实际上可以做哈希表可以做的超集-因此它们不是一回事.可以将其视为哈希表以及其他功能.
So while they're similar, an associative array can actually do a superset of what a hashtable can do - so they're not exactly the same thing. Think of it as hashtables plus extra functionality.
代码示例:
使用关联数组作为哈希表:
$favoriteColor = array();
$favoriteColor['bob']='blue';
$favoriteColor['Peter']='red';
$favoriteColor['Sally']='pink';
echo 'bob likes: '.$favoriteColor['bob']."\n";
echo 'Sally likes: '.$favoriteColor['Sally']."\n";
//output: bob likes blue
// Sally likes pink
遍历关联数组:
$idTable=array();
$idTable['Tyler']=1;
$idTable['Bill']=20;
$idTable['Marc']=4;
//up until here, we're using the array as a hashtable.
//now we loop through the array - you can't do this with a hashtable:
foreach($idTable as $person=>$id)
echo 'id: '.$id.' | person: '.$person."\n";
//output: id: 1 | person: Tyler
// id: 20 | person: Bill
// id: 4 | person: Marc
尤其要注意在第二个示例中,如何根据每个元素在数组中输入的顺序来维护它们的顺序(Tyler,Bill Marc).这是关联数组和哈希表之间的主要区别.哈希表在其持有的项目之间不保持任何联系,而PHP关联数组则可以(甚至可以对PHP关联数组进行排序).
Note especially how in the second example, the order of each element is maintained (Tyler, Bill Marc) based on the order in which they were entered into the array. This is a major difference between associative arrays and hashtables. A hashtable maintains no connection between the items it holds, whereas a PHP associative array does (you can even sort a PHP associative array).
这篇关于哈希表VS关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!