数据结构—————散列表(哈希表)和字典(unity)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/leemu0822/article/details/101374338

散列表(Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表

给定表M,存在函数f(key),对任意给定的关键字值key,代入函数后若能得到包含该关键字的记录在表中的地址,则称表M为哈希(Hash)表,函数f(key)为哈希(Hash) 函数。

为什么我会把散列表和字典放在一起讲呢,其实我字典的本质就是散列表,不过还是有一点区别的,其实散列表也好,字典也好,总结起来就是两个字映射

下面我通过代码来使用一下哈希表和字典

哈希表

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HashTableExample : MonoBehaviour {
    Hashtable table = new Hashtable();

    // Use this for initialization
    void Start () {
        //往哈希表添加元素
        table.Add(1,10); 
        table.Add("pp",99); 
        table.Add('a',"66");

        //取值
        print(table["pp"]);
       
	}
	
	// Update is called once per frame
	void Update () {
	   
	}
}

因为C#已经把我们封装好哈希表了,我们只要会用就行,如果你有兴趣,可以去自己实现一遍,其实也不难,看看结果:

字典

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DictionaryExample : MonoBehaviour
{
    [SerializeField] private InputField En_input;

    [SerializeField] private Button search_btn;

    [SerializeField] private Text cn_text;

    private Dictionary<string,string>EnglishDict=new Dictionary<string, string>();
	// Use this for initialization
	void Start () {
		EnglishDict.Add("below","在下面");
        EnglishDict.Add("expert","专家");
	    EnglishDict.Add("garnered","囊括");
        search_btn.onClick.AddListener(() =>
        {
            if (EnglishDict.ContainsKey(En_input.text))
            {
                cn_text.text = EnglishDict[En_input.text];
            }
        });
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

这是一个简单的通过英文单词查询中文的例子,下面看看效果:

好了,我来总结一下两者的区别,观察上面的代码,你会发现哈希表添加的数据的类型可以是不一样的,本质是object类型,但是字典呢,必须是一样的类型,再者字典是支持泛型的,例如我们可以把Vector3作为key或者Value添加到字典中,而哈希表是不支持的。

这篇文章希望对你有用,最后我把例子上传了github,会持续更新数据结构这方面的内容,会结合一些例子帮助大家更好的理解数据结构,GitHub地址  https://github.com/Leemu0822/UnityDataStruct

猜你喜欢

转载自blog.csdn.net/leemu0822/article/details/101374338