C++-----自己写的哈希表

来源:互联网 发布:阿里云装mysql数据库 编辑:程序博客网 时间:2024/04/30 05:09

Node.CPP

#pragma once

template<class T,class U>
class Node
{
public:


public:
    int key;
int key1;
T data;
int count;
Node<T,U> *panother;


};

Nodeh

#include "StdAfx.h"
#include "Node.h"

MyHash.h


#pragma once
#include "Node.h"
#include<string>
using namespace std;
template<class T,class U>
class MyHash
{
public:
Node<T,U>*p;
T nullvalue;
public:
void put(U key,T data);
T find(U key);
private:
int creat_hash(int num);
int creat_key(int num);
int creat_hash(string num);
int creat_key(string num);
int change_int(int n);
int change_int(string da);
public:
MyHash(void);
~MyHash(void);
};
MyHash.CPP
#include "StdAfx.h"
#include "MyHash.h"


template<class T,class U>
MyHash<T,U>::MyHash(void)
{
p=new Node<T,U>[100];
}


template<class T,class U>
MyHash<T,U>::~MyHash(void)
{
delete []p;
}
template<class T,class U>
int MyHash<T,U>::creat_hash(int num){
  return num%100;
}


template<class T,class U>
int MyHash<T,U>::creat_key(int num){
  return num/100;
}
template<class T,class U>
int MyHash<T,U>::change_int(int n){
return n;
}
template<class T,class U>
int MyHash<T,U>::change_int(string da){
int temp=(int)(da[0]);
return temp;
}
template<class T,class U>
int MyHash<T,U>::creat_hash(string num){
int temp=(int)(num[0]);
//cout<<temp<<endl;
    return temp%100;

}


template<class T,class U>
int MyHash<T,U>::creat_key(string num){
  int temp=(int)(num[1]);
  return temp/100;
}




template<class T,class U>
void MyHash<T,U>::put(U key,T data){


int id=this->creat_hash(key);
if(p[id].count!=1&&p[id].count!=2)
{
p[id].data=data;
p[id].count=1;
p[id].key=change_int(key);
p[id].key1=this->creat_key(key);
//cout<<p[id].key1<<endl;
}
else if(p[id].count==1){

 p[id].panother=new Node<T,U>[100];
 p[id].count=2;
 int key1=this->creat_key(key);
 int key2=this->creat_key(p[id].key);
 p[id].panother[key1].data=data;
 
 p[id].panother[key1].count=1;
 p[id].panother[key1].key=key1;
 p[id].panother[key2].data=p[id].data;
 
 p[id].panother[key2].count=1;
 p[id].panother[key2].key=key2;
}
else{
 int key1=this->creat_key(key);
 p[id].panother[key1].data=data;
 p[id].panother[key1].count=1;
 p[id].panother[key1].key=key1;

}

}
template<class T,class U>
T MyHash<T,U>::find(U key){
int id=this->creat_hash(key);
if(p[id].count==1)
{
if(p[id].key1==this->creat_key(key))
{
return p[id].data;
}
}
else if(p[id].count==2){
   int key1=this->creat_key(key);
return p[id].panother[key1].data;
}
return this->nullvalue;


}
main

#include "stdafx.h"
#include "MyHash.cpp"
#include<iostream>


using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
MyHash<int,int> ihash;
ihash.put(3,56);
ihash.put(5,560);
/*string a="ddd";
ihash.put(a,90);
ihash.put("db",50);
ihash.put("dc",58);*/
//ihash.put("d",20);

//cout<<ihash.find("a")<<endl;
//char r=a[0];


cout<<ihash.find(5)<<endl;
return 0;
}








0 0
原创粉丝点击