温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

简单的哈希表映射试验

发布时间:2020-07-15 11:49:47 来源:网络 阅读:465 作者:Chinayu2014 栏目:编程语言

对于很长的线性数据结构,进行搜索,可以用哈希表的方式。

#include <iostream>
#include <stdio.h>

using namespace std;

//数据类型
//注意:每一个数据节点,须绑定一个唯一的Key值
//这一点可以简单理解为:如果是工人信息,可以使用工号;学生信息,可以用学号
//设备信息,可以用设备编号
struct info
{
    int id;
    char name[10];
};

info data[10]={0};//存储数据

//存入数据
void SetData(int key,const info& value)
{
    int index = key % 10;//简单的散列算法,此处没有避免重复值
    data[index] = value;
}

//查找数据
info find(int key)
{
    int index = key % 10;
    return data[index];
}

int main(int argc, char* argv[])
{
    info a={1001,"张三"};
    SetData(a.id,a);

    info b={1002,"李四"};
    SetData(b.id,b);

    info c = find(1002);
    cout << c.id << ":" << c.name <<endl;

    //一般的数组查询方法
    //    for(int i=0;i<10;i++)
    //    {
    //        if(data[i].id == 1002)
    //        {
    //            cout << c.id << ":" << c.name <<endl;
    //        }
    //    }

    getchar();
    return 0;
}

哈希表的优势在于查找时,一次命中目录。而传统的数组或链表查找,需要从头到尾遍历一次。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI